Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase range from a std::vector?

Tags:

c++

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?

like image 430
jmasterx Avatar asked Mar 17 '11 00:03

jmasterx


People also ask

How do you delete a range of elements in a vector C++?

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.

How do I erase an element from std :: vector <> by value?

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.


1 Answers

Yes, there is an erase function that takes arguments for first and last.

v.erase(v.begin() + 10, v.end());
like image 92
jon_darkstar Avatar answered Sep 22 '22 19:09

jon_darkstar