C ++:如何检测向量中的重复项< string>并打印一份? [英] C++ : How to detect duplicates in vector<string> and print ONE copy?
问题描述
我是C ++的新手。我想知道如何在一个向量中找到重复的字符串,并打印出一个字符串的副本。例如,如果我有<猫,狗,狗,鸟,>它会打印出猫,狗,鸟。我已经排序我的向量和我使用adjacent_find函数和迭代通过向量(因为我必须找到,如果任何单词是重复的)。我的代码检测重复,但它只打印非重复。我想改变它打印出所有的非重复,也只有一个重复,所以在矢量中的所有字符串都打印出来。这是我到目前为止的代码:
I'm new to C++. I was wondering how I can find duplicate strings in a vector and print out ONE copy of the string. For example, if I had <"cat", "dog", "dog", "bird",> it would print out cat, dog, bird. I have sorted my vector and am using the adjacent_find function and iterating through the vector (since I have to find if any word is duplicated). My code detects duplicates, but it only prints out the non-duplicates. I would like to alter it to print out all the non-duplicates and also just ONE of the duplicates, so all strings in the vector are printed out. Here is the code I have so far:
public: void print(vector<string> in) // print method for printing a vector and it's key
{
sort(in.begin(), in.end()); // sort the vector alphabetically first
vector<string>::iterator it;
for( it = in.begin(); it != in.end(); it++ ) // iterate through it
if(adjacent_find(in.begin(), in.end()) == in.end()) // don't print duplicates
cout << *it<<endl; // and print out each string in the vector
}
推荐答案
您可以使用STL算法 std :: unique()
或 std :: unique_copy()
。
You can use the STL algorithms std::unique()
or std::unique_copy()
. They work with any STL container, not just vectors.
将向量打印到标准输出的一个简单示例:
A simple example to print the vector to the standard output:
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> v = { "hello", "hello", "world" };
unique_copy(begin(v), end(v), ostream_iterator<string>(cout, " "));
}
如果要现场执行此操作, code> std :: unique()。重要的是要记住,此函数不会物理删除多余的元素,但它返回迭代器到集合的新逻辑结束:
If you want to perform this operation in-place instead, you can use std::unique()
. It is important to keep in mind that this function does not physically remove the redundant elements, but it returns the iterator to the new logical end of the collection:
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> v = { "hello", "hello", "world" };
auto newEnd = unique(begin(v), end(v));
for_each(begin(v), newEnd, [] (string const& s) { cout << s << " "; });
}
这篇关于C ++:如何检测向量中的重复项< string>并打印一份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!