#include <iostream>
#include <algorithm>
using namespace std;
bool IsOdd (int i) { return i % 2 == 1; } // 奇数
void test_remove(vector<int>& v)
{
auto del = remove(v.begin(), v.end(), 9); // 删除所有的9
v.erase(del, v.end());
//v.erase(del); // 错误的
for(auto& it : v)
cout << it << " "<< endl;
}
void test_remove_if(vector<int>& v)
{
auto del = remove_if(v.begin(), v.end(), IsOdd);
v.erase(del, v.end()); // 删除所有奇数
for(auto& it : v)
cout << it << " "<< endl;
}
int main ()
{
vector<int> v = {1, 2, 3, 4, 6, 9, 10, 12, 9, 55};
//test_remove(v);
test_remove_if(v);
return 0;
}
从vector中删除元素,需要结合erase和remove或remove_if, 且得注意调用方式,否则会得到预料之外的结果!