擦除std :: vector的范围?

时间:2011-03-17 00:48:51

标签: c++

如果我的std::vector有100个元素,而我只想保留前10个元素并删除其余元素,那么有没有方便的方法呢?

4 个答案:

答案 0 :(得分:36)

是的,有一个erase函数,它接受第一个和最后一个参数。

v.erase(v.begin() + 10, v.end());

答案 1 :(得分:26)

vec.resize(10); // drops the rest (capacity remains the same)

答案 2 :(得分:5)

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

答案 3 :(得分:5)

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