C++ List::remove_if() 函式



C++ 的std::list::remove_if()函式用於移除列表中滿足特定條件的元素。它接受一個名為 `pred` 的引數,並移除列表中所有滿足該條件的元素。`pred` 是一個謂詞函式,它是使用者定義的函式,只接受一個引數,該引數的型別必須與列表中儲存的項的型別匹配。

remove_if() 函式不返回任何值,因為函式的返回型別是 void,它會移除列表中所有謂詞函式返回 true 的元素。

語法

以下是 C++ std::list::remove_if() 函式的語法:

void remove_if (Predicate pred);

引數

pred − 這是一個一元謂詞函式,它接受相同型別的數值並返回 true,表示這些值將從列表中移除。

返回值

此函式不返回任何值。

示例 1

在下面的程式中,我們定義了一個名為 Con(int n) 的謂詞函式,它接受一個 int 型別引數,我們使用此函式過濾掉所有大於 2 的值。然後,我們將此函式作為引數傳遞給 remove_if() 函式,以移除列表中所有大於 2 的元素。

#include<iostream>
#include<list>
using namespace std;

//custom function to check condition
bool Con(int n) {
   return (n>2);
}
int main(void) {
   list<int> num_list = {1, 2, 3, 4, 5};
   cout<<"List elements before remove_if operation: "<<endl;
   for(int n : num_list) {
      cout<<n<<" ";
   }
   //using remove_if() function
   num_list.remove_if(Con);
   cout<<"\nList elements after remove_if operation: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   return 0;
}

輸出

這將生成以下輸出:

List elements before remove_if operation: 
1 2 3 4 5 
List elements after remove_if operation: 1 2 

示例 2

以下是 C++ std::list::remove_if() 函式的另一個示例。在這裡,我們定義了一個名為 filter_length(string len) 的謂詞函式,它接受一個字串作為引數。然後,我們將此函式作為引數傳遞給 remove_if() 函式,以移除列表中長度大於 3 的所有字串元素。

#include<iostream>
#include<list>
using namespace std;

bool filter_length(string n) {
   return (n.length()>3);
}
int main(void) {
   list<string> num_list = {"Hello", "how", "are", "you"};
   cout<<"List elements before remove_if operation: "<<endl;
   for(string n : num_list) {
      cout<<n<<" ";
   }
   //using remove_if() function
   num_list.remove_if(filter_length);
   cout<<"\nList elements after remove_if operation: ";
   for(string n : num_list) {
      cout<<n<<" ";
   }
   return 0;
}

輸出

以下是上述程式的輸出:

List elements before remove_if operation: 
Hello how are you 
List elements after remove_if operation: how are you 

示例 3

從列表中移除偶數。

在此示例中,我們定義了一個名為 filter_evens(int n) 的謂詞函式,它接受一個 int 型別引數。然後,我們將此函式作為引數傳遞給 remove_if() 函式,以從當前列表 {1,2,3,4,5,6,7,8,9,10} 中移除所有偶數元素(或數字)。

#include<iostream>
#include<list>
using namespace std;

//custom function to check condition
bool filter_evens(int n) {
   return (n%2 == 0);
}
int main(void) {
   list<int> num_list = {1,2,3,4,5,6,7,8,9,10};
   cout<<"List elements before remove_if operation: "<<endl;
   for(int n : num_list) {
      cout<<n<<" ";
   }
   //using remove_if() function
   num_list.remove_if(filter_evens);
   cout<<"\nAfter removing even numbers from list elements are: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   return 0;
}

輸出

執行上述程式後,它將產生以下輸出:

List elements before remove_if operation: 
1 2 3 4 5 6 7 8 9 10 
After removing even numbers from list elements are: 1 3 5 7 9 
廣告
© . All rights reserved.