【发布时间】:2016-11-06 18:19:41
【问题描述】:
我想弄清楚remove_if 和vector<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
发生了什么事?
【问题讨论】:
标签: c++ stdvector stl-algorithm