Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 931
user2016393 Avatar asked Dec 20 '25 01:12

user2016393


2 Answers

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 << " "; });
}
like image 105
Andy Prowl Avatar answered Dec 21 '25 15:12

Andy Prowl


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.

like image 23
limes Avatar answered Dec 21 '25 14:12

limes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!