C++ STL 中的 forward_list::unique( )


本文將展示 C++ 中 forward_list::unique( ) 函式的執行情況。

正向列表是有序容器,允許在整個順序中進行常量時間的插入和刪除操作。正向列表實現為單鏈表。透過與每個元素關聯到序列中下一個元素的連結來保持排序。

forward_list::unique( ) 是 c++ 標準庫函式,用於從正向列表中刪除所有重複元素。請注意,僅當元素與其後元素比較相等時,才會從 forward_list 容器中移除該元素。因此,此函式對於已排序的列表特別有用。

語法

Forwardlist_name.unique(binarypredicate name)

二進位制謂詞語法

bool 名稱(資料型別 a,資料型別 b)

引數 - 此函式接受一個引數,該引數是一個二進位制謂詞,如果元素應被視為相等,則返回 true。

示例

Output – List : 4, 4, 17, 32, 45, 56, 56, 45, 32, 4, 17, 17
   After Unique operation output is
      Unique list : 4, 17, 32, 45, 56
Output – List : 15.2, 74.0, 3.14, 15.2, 69.5, 74.0, 3.14, 18.5, 3.99
   After Unique operation output is
      Unique list : 3.14, 3.99, 15.2, 18.5, 69.5, 74.0

可以遵循以下方法

  • 首先,我們建立一個二進位制謂詞函式。

  • 然後,初始化正向列表。

  • 然後,定義 unique( ) 函式。

  • 然後,在進行 unique 操作後列印正向列表。

透過使用上述方法,我們可以從 forward 列表中刪除重複元素。

示例

// C++ code to demonstrate the working of forward_list::unique( )
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
// function for binary predicate
bool cmp(int a, int b){
   return (abs(a) == abs(b))
}
int main(){
   // initializing the forward list
   forward_list<int> List = { 2, 4, 6, 3, 5, 3, 4, 4, 9, 1, 6, 6, 2, 2, 9 }
   cout<< " Elements of List:";
   for( auto x = List.start(); x != List.end(); ++x )
      cout<< *x << " ";
   // defining of function that performs the Unique operation
   List.unique();
   cout<< “ Unique List :”;
   for(auto x = List.start(); x != List.end(); ++x)
      cout<< *x << " ";
   return 0;
}

輸出

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

OUTPUT – List : 2, 4, 6, 3, 5, 4, 4, 9, 1, 6, 6, 2, 2, 9
   Unique List : 1, 2, 3, 4, 5, 6, 9
OUTPUT – List : 15.2, 74.0, 3.14, 15.2, 69.5, 74.0, 3.14, 18.5, 3.99
   Unique List : 3.14, 3.99, 15.2, 18.5, 69.5, 74.0

更新時間: 2020-02-28

171 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.