Checking a vector if it "Contains" certain values

std::vector<int> values;

This vector contains 5 values 4,20,8,8,21.

How can I write an if statement or a loop to check if any of those elements contain the same value? As you can see in element 3 and 4 they both contain the value 8. How can I simply obtain which elements within the vector are the same?
Last edited on
If you sort the vector, then elements of same value will be consecutive.

If you use std::multimap, then the vector remains unchanged.
http://www.cplusplus.com/reference/map/multimap/count/
Are you looking for adjacent duplicates (as 8 and 8 in your example), or duplicates in general? C++ provides a function to report the first adjacent duplicate: std::adjacent_find.


Are you looking for adjacent duplicates (as 8 and 8 in your example), or duplicates in general?


I am looking for duplicates in general, they do not need to be in any specific order I just need to know if the vector elements contain duplicates of any kind. Then I would like to be able to write a statement that says

1
2
3
if (the vector contains duplicates){ //Not sure what the syntax would be here
     //Do some kind of action;
}
Last edited on
One of the many ways:

1
2
if (std::set<int>(values.begin(), values.end()).size() != values.size() )
    // Do some kind of action 
if you don't know how to use other data structures, create a copy of the vector and compare each value with the entire vector in a for loop.
Topic archived. No new replies allowed.