Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first N elements from a std::vector

Tags:

c++

stdvector

I can't seem to think of a reliable way (that also compacts memory) to remove the first N elements from a std::vector. How would one go about doing that?

like image 619
ForeverLearning Avatar asked Sep 08 '11 17:09

ForeverLearning


People also ask

How do you delete a first N element from a vector?

Use the . erase() method: // Remove the first N elements, and shift everything else down by N indices myvec.

How do you remove the first element of a vector in C++?

To remove first element of a vector, you can use erase() function. Pass iterator to first element of the vector as argument to erase() function.

How do you remove a specific element from a vector in C++?

The C++ vector has many member functions. Two of these member functions are erase() and pop_back(). pop_back() removes the last element from the vector. In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements.

How do I remove multiple elements from a vector in C++?

If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase approach would move all of the elements from the position to the end multiple times.


1 Answers

Since you mention that you want to compact memory, it would be best to copy everything to a new vector and use the swap idiom.

std::vector<decltype(myvector)::value_type>(myvector.begin()+N, myvector.end()).swap(myvector); 
like image 104
Mark Ransom Avatar answered Sep 20 '22 10:09

Mark Ransom