Linux 拨号vps windows公众号手机端

C++遍历map的方式有哪些

lewis 8年前 (2017-05-20) 阅读数 9 #程序编程
文章标签 c++

在C++中,有以下几种方式可以遍历map:

  1. 使用迭代器:使用begin()和end()函数获取map的起始和终止迭代器,然后使用循环遍历迭代器来访问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;
}
  1. 使用范围for循环:使用范围for循环可以方便地遍历map中的每个元素。
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto& pair : myMap) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
  1. 使用auto关键字:使用auto关键字可以更简洁地遍历map中的每个元素。
std::map<int, std::string> myMap;
// 添加元素到myMap
for(auto pair : myMap) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}

这些都是常用的遍历map的方式,根据个人习惯和需求选择适合的方式即可。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门