Check std::vector has duplicates
Looking in google for std::unique
I found this page cplusplus : unique. I looked at
a) what it did
Removes all but the first element from every consecutive group
So it looks like it does what you want - removes the duplicates.
I then looks at what it returns, and some comments, coming across a problem...
Return value : An iterator to the element that follows the last element not removed.
So the result from 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
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 include
sort(a.begin(), a.end());
e.g.
sort(a.begin(), a.end());
auto it = std::unique( a.begin(), a.end() );
bool wasUnique = (it == a.end() );
The algorithm you're looking for is std::adjacent_find.
// The container must be sorted!
const std::vector<int> sortedVector = {1,2,3,3,4,5};
const bool hasDuplicates = std::adjacent_find(sortedVector.begin(), sortedVector.end()) != sortedVector.end();
Unlike std::unique, std::adjacent_find doesn't modify the container.
As a bonus, std::adjacent_find returns an iterator to the first element in the duplicate "pair":
const auto duplicate = std::adjacent_find(sortedVector.begin(), sortedVector.end());
if (duplicate != sortedVector.end())
std::cout << "Duplicate element = " << *duplicate << "\n";
You should using set
set<int> s(a.begin(), a.end());
return s.size() != a.size();