C++ 程式初始化字典


C++ 沒有像 Python 中那樣名為字典的資料結構,但它擁有具有類似功能的相同資料結構。C++ 支援對映,它在 STL 類 std::map 中可用。對映物件在每個條目中包含一對值,一個是鍵值,另一個是對映值。鍵值用於搜尋和唯一標識對映中的條目。而對映值並不總是唯一的,鍵值在對映中必須始終唯一。讓我們看看如何使用對映。

首先,讓我們看看如何在 C++ 中定義對映資料結構。

語法

#include 
map <data_type 1, data_type 2> myMap;

讓我們舉個例子,看看如何做到這一點 -

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <int, string> myMap;

   //inserting two key-value pairs
   myMap.insert({1, "Hello"});
   myMap.insert({2, "World"});

   //displaying the key-value pairs
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << endl;
   }

   return 0;
}

輸出

1 Hello
2 World

C++ 中的對映可以透過多種方式初始化。其演算法很簡單。

演算法

  • 建立一個對映物件。

  • 在宣告物件的同時為其賦值。

使用初始化列表初始化對映

使用初始化列表初始化對映與在 C++ 中初始化陣列相同。我們只需在宣告對映時分配鍵值對,並用大括號括起來,格式為 {key, value}。語法如下所示。

語法

#include <map>
map <data_type 1, data_type 2> myMap = {{key1, value1}, {key2, value2}};

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <int, string> myMap = {{1, "One"}, {2, "Two"}, {3, "Three"}};

   //displaying the key-value pairs
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << '\n';
   }

   return 0;
}

輸出

1 One
2 Two
3 Three

使用賦值運算子初始化對映

這類似於為陣列中的特定索引賦值。我們不是提及索引,而是將鍵值放在對映下標中,就像在陣列中一樣。

語法

#include 
map <data_type 1, data_type 2> myMap;
myMap[key1] = value1;

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //declaring the map
   map <int, string> myMap;
   myMap[1] = "One";
   myMap[2] = "Two";
   myMap[3] = "Three";

   //displaying the key-value pairs
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << '\n';
   }

   return 0;
}

輸出

1 One
2 Two
3 Three

從另一個對映初始化對映

可能需要將一個映射覆制到另一個對映中,為此,我們可以從另一個對映初始化一個對映。我們透過在宣告時將對映物件傳遞給對映的複製建構函式來利用對映類的複製建構函式。

語法

#include <map>
map <data_type 1, data_type 2> myMap1(myMap2);

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //declaring the map
   map <int, string> myMap;
   myMap[1] = "One";
   myMap[2] = "Two";
   myMap[3] = "Three";

   //copying using copy constructor
   map <int, string> myMap2(myMap);

   //displaying the key-value pairs
   for (auto itr = myMap2.begin(); itr != myMap2.end(); ++itr) {
      cout << itr->first << " " << itr->second << '\n';
   }

   return 0;
}

輸出

1 One
2 Two
3 Three

結論

C++ 中的對映是有序集合,這意味著對映中的元素根據鍵值排序。這使得它比其他類似的資料結構(如無序對映,其中鍵值對未排序)慢。對映中的所有操作都具有對數複雜度,並且在記憶體中以紅黑樹的形式實現。然而,在實踐中,對映非常有用,因為它提供了非常靈活的方式以鍵值對的方式儲存資料。我們已經討論了初始化對映的所有主要方法;儘管還有更多初始化方法,但這些是最直觀的操作方法。

更新於: 2022-12-14

2K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告