sort() and unique() won't work with such a simple int vector. Any suggestions are welcome.
std::vector<int>vec {33,25,11,44,22,20,12,33,59,87,23,53,26,44,26,97,22,32,44,43,44};
std::sort(vec.begin(), vec.end());
std::unique(vec.begin(), vec.end());
int nr = 1;
std::cout << std::endl;
for (auto p = vec.begin(); p!=vec.end(); p++){
std::cout << *p << " ";
if (!(nr++%4)) std::cout << std::endl;
}
returns:
11 12 20 22 23 25 26 32 33 43 44 53 59 87 97 44 44 53 59 87 97 21Note that the numbers are neither sorted, not duplicates are expelled (I marked 44, 53).
**UPD: thanks to the contributors, here's the solution: instead of
std::unique(vec.begin(), vec.end());
we type:
auto last = std::unique(vec.begin(), vec.end());//returns an iterator to non-unique elements
vec.erase(last, vec.end());// and kills them
The std::sort
works fine. As for the std::unique
- it doesn't alter the size of the vector, it just creates a subsequence at the beginning of the vector with a sequence of one copy of all distinct elements. So, as you indicated in your own comment - you need to keep the iterator std::unique
returns, and iterate from the beginning of the vector to that end iterator.