【发布时间】:2021-11-23 03:27:33
【问题描述】:
在以下示例代码中,remove_if 应该删除所有偶数,但它没有按我预期的那样工作。我显然做错了什么,因为输出继续显示一些偶数,接近尾声。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool
myCond(int i) { return i % 2 == 0; }
int
main ()
{
vector<int> myVector = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22};
remove_if(myVector.begin(), myVector.end(), myCond);
for(int i : myVector) cout << i << " ";
cout << endl;
return 0;
}
输出 11 13 15 17 19 16 17 18 19 20 22
【问题讨论】:
-
你已经完成了erase-remove idiom 的一半。您仍然需要进行擦除。您必须经历这两个步骤的过程,这是一个实现细节。
-
Here is an example 说明步骤。