C++中遍历std::map的常用方式包括:1. 范围for循环(C++11+),简洁高效,推荐现代C++使用;2. 传统迭代器遍历,兼容所有标准;3. const_iterator用于只读访问,更安全;4. std::for_each结合lambda表达式,实现函数式风格遍历。推荐优先使用范围for循环。

在C++中,遍历 std::map 有多种方法,可以根据C++标准版本和编码风格选择合适的方式。以下是常用的几种遍历方式。
这是最简洁、推荐的方式,适用于现代C++代码。
#include <map>
#include <iostream>
int main() {
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
for (const auto&amp; pair : myMap) {
std::cout << pair.first << ": " << pair.second << "\n";
}
return 0;
}
说明: auto& 避免复制键值对,const auto& 表示只读访问,提升性能。
适用于所有C++标准,兼容性好。
立即学习“C++免费学习笔记(深入)”;
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}};
for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << "\n";
}
注意: C++11后可用 auto it = myMap.begin() 简化声明。
当你不打算修改map内容时,使用 const_iterator 更安全。
for (std::map<int, std::string>::const_iterator it = myMap.cbegin();
it != myMap.cend(); ++it) {
std::cout << it->first << ": " << it->second << "\n";
}
结合 std::for_each 实现函数式遍历。
#include <algorithm>
std::for_each(myMap.begin(), myMap.end(), [](const auto&amp; pair) {
std::cout << pair.first << ": " << pair.second << "\n";
});
要求: C++14以上支持lambda中的 auto 参数,否则需写完整类型。
基本上就这些常见方式。日常开发推荐使用范围for循环,清晰高效。如果需要修改值,可以去掉 const;若用于函数参数传递,建议用const引用避免拷贝。
以上就是c++++中如何遍历map_c++ map遍历方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号