本例子, 说明如何删除vector中值或者满足某一函数规律的所有值
// 使用 g++ -std=c++11 or clang++ -std=c++11 编译
#include <vector>
#include <iostream>
#include <algorithm>
bool is_odd(int i)
{
return (i % 2) != 0;
}
void print(const std::vector<int> &vec)
{
for (const auto& i: vec)
std::cout << i << ' ';
std::cout << std::endl;
}
int main()
{
// 初始化向量0-9.
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
print(v);
// 删除所有值为5的元素
v.erase( std::remove( v.begin(), v.end(), 5 ), v.end() );
print(v);
// 删除所有奇数
v.erase( std::remove_if(v.begin(), v.end(), is_odd), v.end() );
print(v);
return 0;
}
/*
输出:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 6 7 8 9
0 2 4 6 8
*/