推荐使用范围for循环遍历map,代码简洁高效;2. 可用迭代器遍历,适合需删除或反向遍历场景;3. 反向遍历用rbegin()和rend();4. 避免遍历时修改容器结构,优先用const auto&提升性能。

在C++中,map 是一个关联容器,用于存储键值对(key-value pairs),并自动按键排序。遍历 map 是日常开发中的常见操作。以下是几种常用的遍历方法及示例代码,适用于 C++11 及以上版本。
这是最简洁、易读的遍历方式,适用于大多数现代 C++ 开发场景。
示例:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> scores = {{"Alice", 95}, {"Bob", 87}, {"Charlie", 92}};
for (const auto& pair : scores) {
cout << "Name: " << pair.first << ", Score: " << pair.second << endl;
}
return 0;
}
说明: 使用 const auto& 避免拷贝,提升效率;pair.first 是键,pair.second 是值。
立即学习“C++免费学习笔记(深入)”;
传统方式,兼容性好,适合需要反向遍历或删除元素的场景。
示例:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> scores = {{"Alice", 95}, {"Bob", 87}, {"Charlie", 92}};
for (auto it = scores.begin(); it != scores.end(); ++it) {
cout << "Name: " << it->first << ", Score: " << it->second << endl;
}
return 0;
}
说明: it->first 等价于 (*it).first,指向当前键值对的指针。
如果需要从大到小访问键(即逆序),可以使用反向迭代器。
示例:
for (auto rit = scores.rbegin(); rit != scores.rend(); ++rit) {
cout << "Name: " << rit->first << ", Score: " << rit->second << endl;
}
说明: rbegin() 指向最后一个元素,rend() 指向第一个元素前的位置。
遍历时注意以下几点:
基本上就这些常用方式。现代 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号