映射是 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++ 中显示映射的内容,我们必须使用迭代器,否则很难打印出值。使用迭代器可以很容易地遍历映射中的所有条目并显示它们的值。