Erase range from std :: vector?

If my std::vector has 100 elements and I want to save only the first 10 and erase the rest, is there a convenient way to do this?

+8
c ++
source share
4 answers
 vec.resize(10); // drops the rest (capacity remains the same) 
+20
source share

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

 v.erase(v.begin() + 10, v.end()); 
+23
source share

vec.erase(vec.begin() + 10, vec.begin() + 100);

+5
source share
 theVector.erase(theVector.begin() + 10, theVector.begin() + 100); 
+4
source share

All Articles