C++ STL 中的 list unique( ) 函式


本任務演示 C++ STL 中 list unique( ) 函式的功能。

什麼是 STL 中的 List?

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

什麼是 unique( )?

list unique( ) 用於刪除列表中的所有重複元素。

語法

list_name.unique(binarypredicate name)

二元謂詞的語法

Bool name(data_type a, data_type b)

引數

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

示例

輸入 列表 - 2 2 6 7 9 9 9 10 5 5

輸出 新列表 - 2 5 6 7 9 10

輸入 列表 - 3.14 5.56 7.62 9.00 0.45 7.62 9.00 7.62 0.45 3.00

輸出 新列表 - 0.45 3.00 3.14 5.56 7.62 9.00

可採用的方法

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

  • 然後我們初始化列表。

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

  • 然後我們列印 unique 操作後的列表。

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

示例

/ / C++ code to demonstrate the working of list unique( ) function in STL
#include <iostream.h>
#include<list.h>
Using namespace std;
/ / function for binary predicate
Bool cmp(int a, int b){
   Return (abs(a) == abs(b))
}
int main ( ){
   List<int> list = { 13, 14, 13, 19, 20, 19, 15, 19, 20, 15, 15 };
   / / print the list
   cout<< “ Elements in List: “;
   for( auto x = List.begin( ); x != List.end( ); ++x)
      cout<< *x << “ “;
   / / declaring unique( ) function
   list.unique(cmp);
   / / printing new list after unique operation
   cout<< “List after unique operation: “;
   for( x=list.begin( ); x != list.end( ); ++x)
      cout<< “ “<<*x;
   return 0;
}

輸出

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

Input - Element in List : 13 14 13 19 20 19 15 19 20 15
Output - List after unique operation : 13 14 15 19 20

示例

/ / C++ code to demonstrate the working of list unique( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
/ / function for binary predicate
Bool cmp(float a, float b){
   Return (abs(a) == abs(b))
}
int main ( ){
   List <float>t; list = { 3.14, 5.56, 7.62, 9.00, 0.45, 7.62, 9.00, 7.62, 0.45, 3.00 };
   / / print the list
   cout<< “ Elements in List: “;
   for( auto x = List.begin( ); x != List.end( ); ++x)
      cout<< *x << “ “;
   / / declaring unique( ) function
   list.unique(cmp);
   / / printing new list after unique operation
   cout<< “List after unique operation: ”;
   for( x=list.begin( ); x != list.end( ); ++x)
      cout<< “ “<<*x;
   return 0;
}

輸出

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

Input - Element in List: 3.14 5.56 7.62 9.00 0.45 7.62 9.00 7.62 0.45 3.00
Output - List after unique operation: 0.45 3.00 3.14 5.56 7.62 9.00

更新於:2020年2月26日

297 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告