c++中遍历map有多种方式:1. 范围for循环(C++11)最简洁,推荐使用const auto&避免拷贝;2. 传统迭代器兼容性好,用->访问成员;3. const_iterator用于只读遍历更安全;4. auto可简化迭代器声明;5. 可修改值但不能修改键;6. reverse_iterator实现反向遍历。现代C++推荐优先使用范围for循环。

在C++中,map 是一个关联容器,用于存储键值对(key-value pairs),并且按键有序排列。遍历 map 是日常开发中的常见操作。下面详细介绍几种常用的 C++ map 遍历方式,适用于不同场景和需求。
1. 使用范围 for 循环(C++11 及以上)
这是最简洁、推荐的遍历方式,适用于现代 C++ 开发。
示例代码:
#include <map><br>#include <iostream><br>int main() {<br> std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 85}, {"Charlie", 95}};<br><br> for (const auto& pair : scores) {<br> std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;<br> }<br> return 0;<br>}
说明:使用 const auto& 可以避免不必要的拷贝,提升性能。pair.first 是键,pair.second 是值。
2. 使用迭代器(传统方式)
适用于所有 C++ 标准版本,兼容性好,控制更灵活。
立即学习“C++免费学习笔记(深入)”;
示例代码:
std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 85}};<br><br>for (std::map<std::string, int>::iterator it = scores.begin(); it != scores.end(); ++it) {<br> std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;<br>}
注意:迭代器成员访问使用 ->,因为 it 是指向 pair 的指针类型。
3. 使用 const_iterator(只读遍历)
当你不需要修改 map 内容时,使用 const_iterator 更安全。
for (std::map<std::string, int>::const_iterator it = scores.cbegin(); it != scores.cend(); ++it) {<br> std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;<br>}
优点:确保不会意外修改 map 元素,适合函数参数传递中的只读操作。
4. 使用 auto 简化迭代器声明
C++11 起支持 auto,可大幅简化迭代器写法。
for (auto it = scores.begin(); it != scores.end(); ++it) {<br> std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;<br>}
相比手动写完整类型,更加清晰易读。
5. 遍历时修改值(非键)
map 的键是不可变的,但值可以修改。需使用非 const 引用或迭代器。
// 使用范围 for 修改值<br>for (auto& pair : scores) {<br> pair.second += 5; // 合法:修改值<br> // pair.first = "new"; // 非法:不能修改键<br>}
6. 反向遍历(从大到小)
使用 reverse_iterator 实现逆序输出。
for (auto rit = scores.rbegin(); rit != scores.rend(); ++rit) {<br> std::cout << "Key: " << rit->first << ", Value: " << rit->second << std::endl;<br>}
常用于需要按键降序处理的场景。
基本上就这些常用方式。选择哪种方法取决于你的编译器支持和编码风格。现代 C++ 推荐优先使用基于范围的 for 循环配合 auto,简洁又高效。


