范围for循环最简洁,推荐C++11及以上使用;2. 迭代器兼容性好,适用于传统代码;3. const_iterator确保只读安全;4. std::for_each结合lambda适合函数式风格。优先推荐范围for循环。

在C++中,map 是一种关联容器,用于存储键值对(key-value pairs),并且按键有序排列。遍历 map 是日常开发中的常见操作。以下是 C++ 中遍历 map 的四种常用方法,每种都有其适用场景。
这是最简洁、现代的方式,适用于支持 C++11 及更高标准的编译器。
示例代码:
#include <map>
#include <iostream>
int main() {
std::map<int, std::string> myMap = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
说明:使用 auto& 避免拷贝,提升效率;const 表示只读访问。
这是早期 C++ 常用的方法,兼容性好,逻辑清晰。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <map>
#include <iostream>
int main() {
std::map<int, std::string> myMap = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
说明:通过 it->first 和 it->second 访问键和值。也可用 (*it).first,但前者更常用。
当你明确不修改 map 内容时,使用 const_iterator 更安全,也适用于 const map 对象。
示例代码:
for (std::map<int, std::string>::const_iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
优点:防止意外修改,提高代码健壮性。
适合需要封装处理逻辑或配合算法使用的场景。
示例代码:
#include <algorithm>
std::for_each(myMap.begin(), myMap.end(), [](const std::pair<int, std::string>& pair) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
});
说明:Lambda 表达式捕获每个键值对,写法灵活,适合复杂处理逻辑。
基本上就这些。选择哪种方式取决于你的 C++ 标准支持情况和编码风格偏好。推荐优先使用范围 for 循环,简洁高效。
以上就是c++++怎么遍历map_C++ map容器遍历的四种方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号