當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ List remove_if()用法及代碼示例


描述

C++ 函數std::list::remove_if()從列表中刪除滿足條件的元素。它刪除所有元素謂詞返回真。

聲明

以下是 std::list::remove_if() 函數形式 std::list 頭文件的聲明。

C++98

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

參數

pred- 一元謂詞 that,它采用相同類型的值,並為要從容器中刪除的那些值返回 true。

返回值

沒有任何。

異常

如果保證不扔, 那麽函數永遠不會拋出異常。

時間複雜度

線性,即 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

相關用法


注:本文由純淨天空篩選整理自 C++ List Library - remove_if() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。