C++中遍历map常用迭代器和auto关键字,推荐使用范围for循环结合const auto&高效访问键值对。

在C++中,map 是一种关联容器,用于存储键值对(key-value pairs),并自动根据键进行排序。遍历 map 容器是日常开发中的常见操作,常用的方法包括使用迭代器和 auto 关键字。下面详细介绍这两种方式。
map 提供了 begin() 和 end() 成员函数,分别返回指向第一个元素和末尾之后位置的迭代器。通过循环结合迭代器可以访问每个键值对。
map 的迭代器指向的是 std::pair 类型的对象,first 成员为键,second 成员为值。
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> scores = {{"Alice", 95}, {"Bob", 87}, {"Charlie", 92}};
// 使用普通迭代器遍历
for (map<string, int>::iterator it = scores.begin(); it != scores.end(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
return 0;
}
输出结果:
立即学习“C++免费学习笔记(深入)”;
Key: Alice, Value: 95如果 map 是 const 或你只想进行只读访问,应使用 const_iterator,这样更安全且符合语义。
for (map<string, int>::const_iterator it = scores.cbegin(); it != scores.cend(); ++it) {
cout << it->first << ": " << it->second << endl;
}
C++11 引入了 auto 关键字,编译器可自动推导变量类型,极大简化了迭代器声明。
// 使用 auto 声明迭代器
for (auto it = scores.begin(); it != scores.end(); ++it) {
cout << it->first << " -> " << it->second << endl;
}
C++11 还支持基于范围的 for 循环,结合 auto 可以写出更简洁、易读的代码。
// 范围 for 循环遍历 map
for (const auto& pair : scores) {
cout << pair.first << ": " << pair.second << endl;
}
说明:
// 修改 map 中的 value
for (auto& pair : scores) {
pair.second += 5; // 加分操作
cout << pair.first << "'s new score: " << pair.second << endl;
}
注意:不能通过 pair.first 修改 key,因为 map 中的 key 是不可变的。
基本上就这些。使用 auto 和范围 for 循环是现代 C++ 推荐的方式,代码更清晰、不易出错。迭代器方式在需要反向遍历或精确控制时仍有用武之地。掌握这些方法,能更高效地处理 map 容器。
以上就是C++如何遍历map容器_C++ map迭代器与auto关键字遍历方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号