Home > Enterprise >  Why using erase and unique function to remove duplicate vectors from a 2d vector is adding an extra
Why using erase and unique function to remove duplicate vectors from a 2d vector is adding an extra

Time:06-08

I am using the below code to remove duplicate vectors from a 2d vector

sort(final_vec.begin(), final_vec.end());
final_vec.erase(unique(final_vec.begin(), final_vec.end()));

Can someone explain me why this is happening and what change should I make.

CodePudding user response:

To make it clearer what exactly is going wrong, I'm going to introduce an intermediate variable to store the iterator returned by std::unique.

Your code is equivalent to:

sort(final_vec.begin(), final_vec.end());
auto new_ending_iterator = unique(final_vec.begin(), final_vec.end())
final_vec.erase(new_ending_iterator);

When we check the overloads of std::vector::erase, we see that this is actually the one-argument erase call:

iterator erase( const_iterator pos )
  1. Removes the element at pos.

So this is erasing a single element from final_vec. However, our goal is to erase every element from new_ending_iterator all the way until final_vec.end(). To do so, we use the second overload of erase:

iterator erase( const_iterator first, const_iterator last );
  1. Removes the elements in the range [first, last).

The correct code would therefore look like

sort(final_vec.begin(), final_vec.end());
auto new_ending_iterator = unique(final_vec.begin(), final_vec.end())
final_vec.erase(new_ending_iterator, final_vec.end());

Or, if you really want to keep it all in one line:

sort(final_vec.begin(), final_vec.end());
final_vec.erase(unique(final_vec.begin(), final_vec.end()), final_vec.end());

CodePudding user response:

sort(final_vec.begin(), final_vec.end());
final_vec.erase(unique(final_vec.begin(), final_vec.end()));

I made changes in the second line and it worked for me.

Apparently vector:erase have a couple overloads, one to delete single element and other to delete all element from unique until we reach the end. I was using first one which was doing some wrong but now with a change, its working for me.

Syntax for second overload of vector:erase and the solution for this error is below

sort(final_vec.begin(), final_vec.end());
final_vec.erase(unique(final_vec.begin(), final_vec.end()), final_vec.end());
  • Related