从 std::vector 中删除一定范围内的元素?

19
如果我的 std::vector 有100个元素,我只想保留前10个并删除其余的,是否有方便的方法可以做到这一点?
4个回答

58

是的,有一个具有first和last参数的erase函数。

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

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

如果元素没有默认构造函数,这将无法工作。 - Fan

6

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


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接