unique
doesn't remove anything from the vector.
unique
rearranges the vector so that all the duplicates are at the end of vector, but they're still in there.
what does the unique method return? |
unique
returns an iterator indicating the position in the vector where those duplicates begin.
Here's an example:
vector before unique: { 3 , 4 , 4 , 5, 5, 5 , 6 , 7 , 7 , 8}
vector after unique: { 3 , 4 , 5 , 6 , 7 , 8 , x , x , x , x}
and the returned value is an iterator indicating that first 'x' value.
All those 'x' values; they're still in the vector. the vector is the same size, all the duplicates have been moved to the end and each of those 'x' values is some duplicate item.
erase
is then actually removing items from the vector. In the code above,
erase
is removing all the duplicate items that were moved to the end of the vector. How does it know where to start? Because it is passed an iterator that
unique
gave back, indicating where those duplicates begin.