C++程式使用字典字面量建立字典


C++ 中沒有字典,但它有一個類似的結構叫做 map。map 的每個條目包含一對值,分別是鍵和對映值。鍵值用於索引每個條目,而對映值是與鍵關聯的值。鍵是唯一的,但對映值可能唯一也可能不唯一。在本文中,我們將瞭解如何初始化 map 物件並從另一個 map 物件建立它。

建立空 map

要建立 map 物件,我們需要匯入 STL 類 std::map。當我們建立 map 物件時,會建立一個空 map。需要注意的是,在建立 map 物件時,我們必須指定鍵和對映值的型別。

語法

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

讓我們來看一個例子 -

示例

#include <iostream>
#include <map>

using namespace std;

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

   //inserting some values
   mmap.insert({"Fruit", "Mango"});
   mmap.insert({"Tree", "Oak"});
   mmap.insert({"Vegetable", "Eggplant"});

   //displaying the contents
   for (auto itr = mmap.begin(); itr != mmap.end(); ++itr) {
      cout << itr->first << ": " << itr->second << endl;
   }

   return 0;
}

輸出

Fruit: Mango
Tree: Oak
Vegetable: Eggplant

從另一個 map 建立 map

在某些情況下,我們可能需要複製 map 或需要保留其值。為此,我們可以使用 map 類的複製建構函式從另一個 map 建立 map。我們需要確保兩個 map 物件的資料型別匹配。

語法

#include <map>
map <data_type 1, data_type 2> map_name1;
map <data_type 1, data_type 2> map_name2(map_name1);

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"Fruit", "Litchi"}, {"Tree", "Birch"}, {"Vegetable", "Potato"}};

   //copy the elements using the copy constructor
   map <string, string> copyMap(mmap);

   //displaying the contents
   for (auto itr = copyMap.begin(); itr != copyMap.end(); ++itr) {
      cout << itr->first << ": " << itr->second << endl;
   }
   return 0;
}

輸出

Fruit: Litchi
Tree: Birch
Vegetable: Potato

結論

map 是 C++ 中的有序集合,這意味著元素根據其鍵值排序。map 在記憶體中使用紅黑樹實現,併為所有操作提供對數時間複雜度。在本文中,我們瞭解瞭如何使用複製建構函式建立 map 物件的副本。

更新於: 2022-12-13

14K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告