C++ : How to detect duplicates in vector<string> and print ONE copy?

不打扰是莪最后的温柔 提交于 2019-12-14 01:32:26

问题


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
}

回答1:


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, " "));
}

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 << " "; });
}



回答2:


Try std::unique, which removes all but the first element from every consecutive group of identical elements (more examples + information here). Since your vector is sorted, this sounds like what you'd like.




回答3:


If your vector is already sorted, you can use std::unique to remove consecutive duplicates.

Another alternative is to construct an std::set from the vector. That will have unique elements by design.



来源:https://stackoverflow.com/questions/14552633/c-how-to-detect-duplicates-in-vectorstring-and-print-one-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!