当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ Forward_list remove_if()用法及代码示例



描述

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

声明

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

C++11

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

参数

pred- 一元谓词 that,它采用相同类型的值,并为要从容器中删除的那些值返回 true。

返回值

异常

如果保证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

相关用法


注:本文由纯净天空筛选整理自 C++ Forward_list Library - remove_if() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。