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

Is there any standard variadic function for erasing multiple elements in a vector?

Take this vector:

std::vector<int> v = {1, 2, 3, 4, 5};

Let’s say I want to remove some elements of a vector at some arbitrary indices: 0, 1, and 3. It’s tedious to have to write something like this:

v.erase(v.begin());
v.erase(v.begin());
v.erase(v.begin() + 1);

Is there any standard function that takes in an arbitrary number of indices to erase from a vector? Something like this: v.erase(0, 1, 3);

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 :

Yes and no.

There’s nothing that deals with indices. There’s also nothing that deals with arbitrary elements.

But you can erase multiple items that form a contiguous range at once. So you can coalesce your first two calls to erase into one (and probably about double the speed in the process).

// erase the first two elements
v.erase(v.begin(), v.begin() + 2);
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