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

