Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why using erase and unique function to remove duplicate vectors from a 2d vector is adding an extra empty vector in 2d vector?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading