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
}
You can use the STL algorithms
std::unique()orstd::unique_copy(). They work with any STL container, not just vectors.A simple example to print the vector to the standard output:
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: