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?
Use the . erase() method: // Remove the first N elements, and shift everything else down by N indices myvec.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With