C++ STL 中 set 和 unordered_set 的區別(3)


在本文中,讓我們瞭解 C++ STL 中的 set 和 unordered_set 是什麼,從而瞭解它們之間的區別。

什麼是 set?

set 是一種關聯容器,它包含一組按 Key 型別排序的唯一物件。每個元素只能出現一次,因此不允許重複。使用者可以透過任何順序插入元素來建立 set,而 set 會向用戶返回排序後的資料,這意味著 set 包含用於排序資料的定義,這些定義對使用者是抽象的。

使用 set 的主要原因是

  • 當需要排序後的資料

  • 當不需要重複值,只需要唯一資料時

  • 當我們想要使用二叉搜尋樹而不是雜湊表時。

  • 當搜尋時間沒有問題時,因為它在搜尋中需要log(n) 的複雜度

輸入

set = {2, 1, 5, 6, 9, 3, 2}

輸出

1, 2, 3, 5, 6, 9

注意 − 值以隨機順序插入,但它們按 set 排序,並且重複值也會從 set 中刪除。

示例

 線上演示

#include <iostream>
#include <set>
using namespace std;
int main(){
   //creating an array
   int arr[] = {2, 1, 5, 6, 9, 3, 2};
   int size = sizeof(arr)/ sizeof(arr[0]);
   //declaring a set
   set<int> SET;
   //inserting elements from an array to set using insert()
   for(int i = 0; i<size; i++){
      SET.insert(arr[i]);
   }
   set<int>::iterator it;
   cout<<"Values in set are: ";
   for(it = SET.begin(); it != SET.end(); it++){
      cout <<*it<<" ";
   }
}

輸出

上面程式碼的輸出將是 −

Values in set are: 1 2 3 5 6 9

什麼是 unordered_set?

unordered_set 是一種關聯容器,它包含一組以隨機方式插入的無序資料。每個元素只能出現一次,因此不允許重複。使用者可以透過任何順序插入元素來建立 unordered_set,並且 unordered_set 將以任何順序(即無序形式)返回資料。

使用 unordered_set 的主要原因是

  • 當不需要排序資料時,這意味著資料以無序格式提供

  • 當不需要重複值,只需要唯一資料時

  • 當我們想要使用雜湊表而不是二叉搜尋樹時。

  • 當需要更快的搜尋時,因為它在平均情況下需要 O(1) 的時間複雜度,而在最壞情況下需要 O(n) 的時間複雜度

輸入

set = {2, 1, 5, 6, 9, 3, 2}

輸出

3, 9, 6, 5, 2

示例

 線上演示

#include <iostream>
#include <unordered_set>
using namespace std;
int main (){
   int arr[] = { 2, 1, 5, 6, 9, 3, 2 };
   int size = sizeof (arr) / sizeof (arr[0]);
   unordered_set < int >U_SET;
   //inserting elements from an array to an unordered_set using insert()
   for (int i = 0; i < size; i++){
      U_SET.insert (arr[i]);
   }
   unordered_set < int >::iterator it;
   cout << "Values in unordred set are: ";
   for (it = U_SET.begin (); it != U_SET.end (); it++){
      cout << *it << " ";
   }
}

輸出

上面程式碼的輸出將是 −

Values in unordered set are: 3 6 5 9 2 1

更新於: 2020年6月6日

906 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.