目录

forward_list::remove_if

描述 (Description)

C ++函数std::forward_list::remove_if()从forward_list中删除满足条件的元素。 它删除谓词返回true的所有元素。

声明 (Declaration)

以下是std :: forward_list :: remove_if()函数形式std :: forward_list头的声明。

C++11

template <class Predicate>
void remove_if (Predicate pred);

参数 (Parameters)

pred - 一元谓词,它取一个相同类型的值,并返回true,以便从容器中删除这些值。

返回值

没有

异常 (Exceptions)

如果pred保证no_throw ,那么函数永远不会抛出异常。

时间复杂

线性即O(n)

例子 (Example)

以下示例显示了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
↑回到顶部↑
WIKI教程 @2018