Erase–remove惯用法Erase–remove惯用法'是C++程序设计语言常用的技术,用于在C++标准模板库容器中删除元素。[1][2][3] 动机一个常见的编程任务是从集合(collection)中删除等于某个值或满足某个标准的所有元素。C++语言可以通过手写循环完成这个任务。但更好的办法是使用C++标准模板库中的算法来实现。[1][2][3]
由于没有元素被删除,因此容器尺寸保持不变。容器尾部的元素都是需要被删除的,但其状态未指定(unspecified state)。 同样的事情(删除多个元素),用容器的方法 局限erase–remove惯用法不能用于返回
例子// Use g++ -std=c++11 or clang++ -std=c++11 to compile.
#include <algorithm> // remove and remove_if
#include <iostream>
#include <vector> // the general-purpose vector container
bool IsOdd(int i) { return i & 1; }
void Print(const std::vector<int>& vec) {
for (const auto& i : vec) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
int main() {
// Initializes a vector that holds numbers from 0-9.
std::vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Print(v);
// Removes all elements with the value 5.
v.erase(std::remove(v.begin(), v.end(), 5), v.end());
Print(v);
// Removes all odd numbers.
v.erase(std::remove_if(v.begin(), v.end(), IsOdd), v.end());
Print(v);
}
/*
Output:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 6 7 8 9
0 2 4 6 8
*/
参考文献
|