用 C++ 程式建立空字典


對映是 C++ 中的資料結構,可以在 STL 類 std::map 中找到。它類似於我們在 Python 中看到的字典。對映物件中的每個條目都有一對值,其中之一是鍵值,另一個是對映值。使用鍵值查詢和唯一標識對映中的條目。對映中的鍵值必須始終唯一,但不需要對映值唯一。在本文中,我們重點介紹建立空對映物件。

建立空對映

我們只建立一個對映物件,結果就是一個空對映。語法如下。

語法

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

我們來看一個示例 −

示例

#include <iostream>
#include <map>

using namespace std;

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

   //displaying the contents, it returns nothing as it is empty
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << endl;
   }

   return 0;
}

輸出

執行程式碼不會顯示任何內容,因為對映為空。

建立零初始化對映

僅當對映的值型別為整數時才可執行此操作。即使我們引用對映中沒有的鍵,返回的值也是 0。

語法

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

示例

#include <iostream>
#include <map>

using namespace std;

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

   //displaying the contents, it returns 0 as it is empty
   for (auto itr = myMap.begin(); itr != myMap.end(); ++itr) {
      cout << itr->first << " " << itr->second << endl;
   }
   cout<< myMap["test"] << endl;

   return 0;
}

輸出

0

結論

對映是 C++ 中的有序集合,這意味著元素根據其鍵值進行排序。對映是在記憶體中使用紅黑樹實現的。當初始化對映物件時,所有對映都是空的,但零初始化對映僅在對映值型別為整數時可用。

更新於: 13-12-2022

610 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始學習
廣告
© . All rights reserved.