且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

迭代时从向量中删除项目?

更新时间:2022-06-18 23:58:41

过去我做过的最易读的方法是使用 std::vector::erase 结合 std::remove_if.在下面的示例中,我使用此组合从向量中删除任何小于 10 的数字.

The most readable way I've done this in the past is to use std::vector::erase combined with std::remove_if. In the example below, I use this combination to remove any number less than 10 from a vector.

(对于非 c++0x,您可以将下面的 lambda 替换为您自己的谓词:)

// a list of ints
int myInts[] = {1, 7, 8, 4, 5, 10, 15, 22, 50. 29};
std::vector v(myInts, myInts + sizeof(myInts) / sizeof(int));

// get rid of anything < 10
v.erase(std::remove_if(v.begin(), v.end(), 
                       [](int i) { return i < 10; }), v.end());