首頁 > 後端開發 > C++ > 主體

C++程式將陣列轉換為集合(雜湊集合)

PHPz
發布: 2023-09-16 09:01:02
轉載
672 人瀏覽過

C++程式將陣列轉換為集合(雜湊集合)

陣列是 C 中可用的資料結構,用於保存相同類型元素的順序集合。數組的大小是固定的,但可以根據需要擴展或縮小。將數組視為相同類型變數的集合很重要,即使它用於儲存資料集合。集合(或在本例中為無序集合)是一種以任意順序儲存特定資料類型的元素的容器。哈希表用於實現 unordered_set,其中鍵被哈希到哈希表索引中,以幫助確保插入始終是隨機的。

可以使用我們進一步討論的各種方法來完成從陣列到無序集的轉換。

將陣列元素一一插入集合中

將陣列轉換為無序集的最簡單方法是使用 for 迴圈並將每個陣列元素單獨插入到無序集中。接下來我們來看看語法和演算法。

文法

int ip[] = <integer array>;
   unordered_set<int> op;
   for( int i : ip) {
      op.insert(i);
}
登入後複製

演算法

  • 在整數陣列 ip 中取得輸入。
  • 定義一個 unordered_set 操作。
  • 對於數組 ip 中的每個元素 i,執行 -
    • 將 IP 插入 op。
  • 顯示op的內容。

範例

#include <bits/stdc++.h>
using namespace std;

template <size_t N> unordered_set<int> solve( int (&ip)[N] )
{
   //an unorderd set is declared
   unordered_set<int> op;
   
   //each element is inserted using insert function
   for(int i : ip) {
      op.insert(i);
   }
   return op;
}
int main()
{
   int ip[] = {50, 80, 90, 40, 30};
   unordered_set<int> op = solve(ip);

   //display the input
   cout<< "The input array is: ";
   for(int i : ip) {
      cout<< i << " ";
   }

   //display the output
   cout<< "\nThe output set is: ";
   for(int j : op) {
      cout<< j << " ";
   }
   return 0;
}
登入後複製

輸出

The input array is: 50 80 90 40 30 
The output set is: 30 40 90 50 80
登入後複製

我們宣告了一個整數數組 ip 並迭代數組中的所有元素。我們將輸出集宣告為 op,並使用容器中可用的插入函數將每個元素插入到無序集中。我們可以看到的結果是一組無序的值,這些值也存在於陣列中。

使用範圍建構子建構集合

也可以使用其範圍建構函式建立 unordered_set。範圍構造函數有兩個輸入;輸入陣列的起始指標以及加上起始指標的輸入陣列的大小。

文法

int ip[] = ;
int n = sizeof(ip) / sizeof(ip[0]);
std::unordered_set op(ip, ip + n);
登入後複製

演算法

  • 在整數陣列 ip 中取得輸入。
  • 使用 sizeof 運算子決定輸入陣列的大小。
  • 將陣列的大小分配給整數變數 n。
  • 使用陣列起始指標和陣列大小建構一個 unordered_set 操作。
  • 顯示op的內容。

範例

#include <bits/stdc++.h>
using namespace std;

template <size_t N> unordered_set<int> solve(int (&ip)[N]) {
   //the size is determined of the input array
   int n = sizeof(ip) / sizeof(ip[0]);

   //output set is constructed using range constructor
   std::unordered_set<int> op(ip, ip + n);
   return op;
}

int main()
{
   int ip[] = {30, 20, 50, 10, 70};
   unordered_set<int> op = solve(ip);

   //display the input
   cout<< "The input array is: ";
   for(int i : ip) {
      cout<< i << " ";
   }  

   //display the output
   cout<< "\nThe output set is: ";
   for(int j : op) {
      cout<< j << " ";
   }
   return 0;
}
登入後複製

輸出

The input array is: 30 20 50 10 70 
The output set is: 70 10 50 20 30
登入後複製

在此範例中,我們必須使用 sizeof 函數來確定陣列的大小。我們 將大小分配給變數 n 並使用指標 ip 和 ip n 建立 unordered_set 操作。

結論

unordered_set 能夠包含任何類型的資料。要更改它所保存的資料類型,我們必須更改 中包含的資料類型。該容器很好地支援原始類型和使用者定義類型。實際上,unordered_set 工作得很好,通常提供恆定時間的搜尋操作。 unordered_set 上的所有操作通常都需要恆定時間 O(1),儘管在最壞的情況下,它們可能需要長達線性時間 O(n),具體取決於內部雜湊函數。

以上是C++程式將陣列轉換為集合(雜湊集合)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!