c++algorithmfor-loopvectorduplicates

Check std::vector has duplicates


I want to check if a vector of integers has any duplicates or not, and have to return true if it does. So I try to do something like this:

vector<int> uGuess = {1,2,3,3,4,5}
vector<int> a = uGuess;
sort(a.begin(), a.end());
bool d = unique(a.begin(), a.end());

And this will not work since unqiue cannot be assigned as a bool value. How should I proceed towards this? If I were to write a for loop to perform the same action, how should I do that?


Solution

  • Looking at google for std::unique I found this page std::unique. I looked at what it did:

    Eliminates all except the first element from every consecutive group of equivalent elements from the range [first, last)

    So it looks like it does what you want - removes the duplicates.

    I then looked at what it returns...

    ... returns a past-the-end iterator for the new logical end of the range

    So the result from std::unique is a sequence which is not necessary the same as the whole vector.

    If nothing was removed, the return value would be the end of the vector.

    So you want:

    vector<int>::iterator it = std::unique(a.begin(), a.end());
    bool wasUnique = (it == a.end());
    

    Or for C++11:

    auto it = std::unique(a.begin(), a.end());
    bool wasUnique = (it == a.end());
    

    Finally for the unique function to work, the vector needs to be sorted, so the complete code would be:

    sort(a.begin(), a.end());
    auto it = std::unique(a.begin(), a.end());
    bool wasUnique = (it == a.end());