C++ STL 中的 list_remove() 和 list remove_if()


本任務旨在展示 C++ STL 中 list remove() 和 list remove_if() 函式的功能。

什麼是 STL 中的 List?

List 是一種容器,允許在序列中的任何位置進行常數時間插入和刪除。List 以雙向連結串列的形式實現。List 允許非連續記憶體分配。與陣列、向量和雙端佇列相比,List 在任何位置插入、提取和移動元素方面效能更好。在 List 中,對元素的直接訪問速度較慢,並且 List 類似於 forward_list,但 forward_list 物件是單向連結串列,只能向前迭代。

什麼是 remove()?

此函式用於移除傳遞給函式的引數中的給定值。

語法

listname.remove(val);

引數

val − 定義要移除的值。

示例

Input List: 1 2 3 3 4 5
Output New List: 1 2 4 5
In this List element 3 is removed.

Input List: 5 6 7 8 8 8 9
Output New List: 5 7 8 8 8 9
In this list element 6 in removed

可以遵循的方法

  • 首先,我們宣告 List。

  • 然後我們列印 List。

  • 然後我們定義 remove() 函式。

透過使用上述方法,我們可以移除給定的元素。

示例

// C++ code to demonstrate the working of list remove( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List<int> list = { 21, 24, 28, 26, 27, 25 };
   // print the list
   cout<< " list: ";
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << " ";
   // defining remove( ) function
   list.remove(27);
   cout<< " New List:”;
   for( x = list.begin( ); x != list.end( ); ++x)
      cout<<' " " << *x;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出

Input - List: 21 24 28 26 27 25
Output - New List: 21 24 28 26 25
Input – List: 45 46 47 48 49 50
Output – New List: 45 46 48 49 50

什麼是 remove_if() 函式?

此函式用於移除返回值為真的謂詞或返回值為真的條件(作為引數傳遞)的值。

語法

listname.remove_if(predicate)

引數

predicate − 定義作為引數傳遞的條件。

示例

Input – List: 5 6 7 8 9 10
Output – New List: 5 7 9
In this list we remove all the even elements.

Input – List:5 10 15 20 25 30
Output – New List: 5 15 25
In this List we remove all the elements which is divisible by 10.

可以遵循的方法

  • 首先,我們宣告謂詞函式。

  • 然後我們宣告列表。

  • 然後我們列印列表。

  • 然後我們宣告 remove_if() 函式。

透過使用上述方法,我們可以根據任何給定條件移除元素。在宣告 remove_if() 函式時,我們將謂詞作為引數傳遞。

示例

// C++ code to demonstrate the working of list remove_if( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
Bool div3( const int& val){
   return( val % 3) == 0);
}
int main( ){
   List<int> list = { 2, 3, 4, 15, 9, 7, 21, 24, 13 };
   cout<< " List: ";
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << " ";
   // declaring remove_if( ) function
   list.remove_if(div3);
   cout<< " New List:”;
   for( x= list.begin( ); x != end( ); ++x)
      cout<< " " << *x;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出

Input – List: 2 3 4 15 9 7 21 24 13
Output – New List: 2 4 7 13

更新於: 2020年3月5日

146 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告