C++ 程式列印字典


在 C++ 中,對映是一種特殊的容器,其中每個元素都是一對兩個值,即鍵值和對映值。鍵值用於索引每個專案,對映值是與鍵關聯的值。鍵始終是唯一的,而不管對映值是否唯一。要在 C++ 中列印對映元素,我們必須使用迭代器。迭代器物件指示一組專案中的一個元素。迭代器主要與陣列和其他型別的容器(如向量)一起使用,並且具有一組特定的操作,這些操作可用於識別特定範圍內的特定元素。可以增加或減少迭代器以引用存在於範圍或容器中的另一個元素。迭代器指向範圍特定元素的記憶體位置。

使用迭代器在 C++ 中列印對映

首先,我們看一下如何定義迭代器以列印對映的語法。

語法

map<datatype, datatype> myMap;
map<datatype, datatype > :: iterator it;
for (it = myMap.begin(); it < myMap.end(); it++)
      cout << itr->first << ": " << itr->second << endl;

另一種方法是這樣的:

map<datatype, datatype> mmap;
for (auto itr = my.begin(); itr != mmap.end(); ++itr) {
   cout << itr->first << ": " << itr->second << endl;
}

讓我們舉一個使用這兩種方法的例子:

示例

#include <iostream>
#include <map>

using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"City", "Berlin"}, {"Country", "Germany"}, {"Continent", "Europe"}};
   map <string, string>::iterator itr;

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

輸出

City: Berlin
Continent: Europe
Country: Germany

使用第二種方法:

示例

#include <iostream>
#include <map>
using namespace std;

int main() {
   //initialising the map
   map <string, string> mmap = {{"City", "London"}, {"Country", "UK"}, {"Continent", "Europe"}};

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

輸出

City: London
Continent: Europe
Country: UK

結論

要顯示 C++ 中對映的內容,我們必須使用迭代器,否則很難打印出值。使用迭代器,可以非常輕鬆地遍歷對映中的所有條目並顯示其值。

更新於: 2022-12-13

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.