映射是 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 中顯示映射的內容,我們必須使用迭代器,否則很難列印出值。使用迭代器可以輕鬆地遍歷映射中的所有條目並顯示它們的值。
以上是C++程式列印字典的詳細內容。更多資訊請關注PHP中文網其他相關文章!