I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)
vector<int> nums2 = {1,2,3,4};
vector<int> nums = {1,2,3,1};
cout << "nums1" << endl;
vector<int> a(nums.begin(), nums.end());
auto ip = unique(nums.begin(), nums.begin()+nums.size());
nums.resize( std::distance(nums.begin(),ip) );
cout << a.size() << " " << nums.size() << endl;
cout << "Nums2" << endl;
vector<int> a2(nums2.begin(), nums2.end());
auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
nums2.resize( std::distance(nums2.begin(),ip2) );
cout << a2.size() << " " << nums2.size();
The actual output is
nums1
4 4
Nums2
4 4
but it should have been
nums1
4 3
Nums2
4 4
std::unique
only removes consecutive duplicates. From cppreference.com on std::unique
:
Eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.
Your 1s are not consecutive so they aren't removed. This is the expected behavior. A quick solution is to first std::sort
your range.