欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > C++: Map数组的遍历

C++: Map数组的遍历

2025/9/30 17:30:28 来源:https://blog.csdn.net/Ethan_Rich/article/details/140179764  浏览:    关键词:C++: Map数组的遍历

在C++中,map是一个关联容器,它存储的元素是键值对(key-value pairs),其中每个键都是唯一的,并且自动根据键来排序。遍历map的方式有几种,但最常用的两种是使用迭代器(iterator)和范围基于的for循环(C++11及以后版本)。这里我将展示这两种方法的示例。

使用迭代器遍历map

#include <iostream>  
#include <map>  
#include <string>  int main() {  // 创建一个map  std::map<std::string, int> myMap = {  {"apple", 100},  {"banana", 200},  {"cherry", 300}  };  // 使用迭代器遍历map  for (std::map<std::string, int>::iterator it = myMap.begin(); it != myMap.end(); ++it) {  std::cout << it->first << ": " << it->second << std::endl;  }  // 或者使用auto关键字简化迭代器类型  for (auto it = myMap.begin(); it != myMap.end(); ++it) {  std::cout << it->first << ": " << it->second << std::endl;  }  return 0;  
}

使用范围基于的for循环遍历map(C++11及以后)

#include <iostream>  
#include <map>  
#include <string>  int main() {  // 创建一个map  std::map<std::string, int> myMap = {  {"apple", 100},  {"banana", 200},  {"cherry", 300}  };  // 使用范围基于的for循环遍历map  for (const auto& pair : myMap) {  std::cout << pair.first << ": " << pair.second << std::endl;  }  return 0;  
}

在这个例子中,pairmap中的一个键值对,pair.first是键,pair.second是值。注意,这里使用了const auto&来避免不必要的拷贝,因为map中的元素是常量引用,这样可以使代码更高效。

以上就是C++中遍历map的两种常用方法。选择哪种方法取决于你的具体需求和C++版本。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词