If my std::vector
has 100 elements, and I only want to keep the first 10 and erase the rest, is there a convenient way to do this?
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
Yes, there is an erase function that takes arguments for first and last.
v.erase(v.begin() + 10, v.end());
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