C++ List 库 - remove_if() 函数
描述
C++ 函数 std::list::remove_if() 从列表中删除满足条件的元素。 它删除所有 predicate 返回 true 的元素。
声明
以下是 std::list::remove_if() 函数形式 std::list 头的声明。
C++98
template <class Predicate> void remove_if (Predicate pred);
参数
pred − 一元谓词 that,它接受一个相同类型的值,并为要从容器中删除的值返回 true。
返回值
None.
异常
如果 pred 保证 not throw,则函数永远不会抛出异常。
时间复杂度
线性,即 O(n)
示例
以下示例显示了 std::list::remove_if() 函数的用法。
#include <iostream>
#include <list>
using namespace std;
bool foo(int n) {
return (n > 5);
}
int main(void) {
list<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << "Contents of list before remove_if operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
/* remove all elements larger than 5 */
l.remove_if(foo);
cout << "Contents of list after remove_if operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Contents of list before remove_if operation 1 2 3 4 5 6 7 8 9 Contents of list after remove_if operation 1 2 3 4 5

