使用算法擦除向量中的特定元素

Erasing particular elements in a vector with algorithm

我想弄清楚 remove_ifvector<T>::erase 是如何工作的。我有下面的代码(试图删除奇数元素):

v2.clear();
v2 = { 10, 20, 21, 30, 31, 33, 44, 66, 67 }; //vector<int>
cout << "v2 is now: " << endl;
printCollection(v2);    
cout << "Trying to remove odds from v2: " << endl;
auto what = remove_if(begin(v2), end(v2), [](int elem) {return elem % 2 != 0;});
v2.erase(begin(v2), what);
printCollection(v2);

这是输出:

v2 is now:
10 20 21 30 31 33 44 66 67

Trying to remove odds from v2:
33 44 66 67

这是怎么回事?

您的代码的行为未指定。 std::remove_if 将所有未删除的元素移动到容器的前面,returns 新的逻辑结束迭代器。此新端(代码中的 what)和 .end() 之间的所有元素都具有未指定的值。

您应该从 what 擦除到 .end()

v2.erase(what, end(v2));

demo