在C++中,有以下几种方式可以遍历map:
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
这些都是常用的遍历map的方式,根据个人习惯和需求选择适合的方式即可。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 如何分享和传播C++ Primer PDF