C++ forward_list 库 - remove_if() 函数



描述

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

声明

以下是来自 std::forward_list 头文件的 std::forward_list::remove_if() 函数的声明。

C++11

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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

参数

pred - 一元谓词,它接受相同类型的值并返回 true,表示要从容器中移除的值。

返回值

异常

如果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
forward_list.htm
广告