
映射是 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;
}
让我们举一个使用这两种方法的例子 -
系统介绍 45°C 商城系统,以 Thinkphp5.0 + Uniapp + Layui2.9 + Vue 为技术基石,精心打造出的全新 MINI 商城应用。其功能覆盖全面,无论是 PC 商城、H5 商城,还是公众号商城、微信小程序以及抖音小程序的制作都能完美胜任。采用标准系统结合插件模式开发,用户能够极为便捷地定制专属的个性模块。整个系统,从程序设计到 UI 呈现,都秉持着一贯的小而美理念。程
0
立即学习“C++免费学习笔记(深入)”;
#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中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号