在c++标准库中,unordered_map是基于哈希表实现的键值对容器,存储的元素是无序的,遍历它有多种不同的实现方式,开发者可以根据代码场景选择最合适的方法。

迭代器遍历方式
迭代器是遍历unordered_map最基础的方式,通过获取容器的起始迭代器和结束迭代器,逐个访问元素。这种方式兼容性较好,支持c++11之前的版本。
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
// 创建并初始化unordered_map
std::unordered_map<int, std::string> my_map;
my_map[1] = "apple";
my_map[2] = "banana";
my_map[3] = "orange";
// 使用迭代器遍历
for (std::unordered_map<int, std::string>::iterator it = my_map.begin(); it != my_map.end(); ++it) {
std::cout << "key: " << it->first << ", value: " << it->second << std::endl;
}
// c++11之后可以使用auto简化迭代器声明
for (auto it = my_map.begin(); it != my_map.end(); ++it) {
std::cout << "key: " << it->first << ", value: " << it->second << std::endl;
}
return 0;
}
范围for循环遍历
c++11引入了范围for循环,遍历unordered_map的代码会更加简洁,不需要手动声明迭代器,可读性更强。
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<int, std::string> my_map;
my_map[1] = "apple";
my_map[2] = "banana";
my_map[3] = "orange";
// 范围for循环遍历,元素类型为std::pair<const int, std::string>
for (const auto& pair : my_map) {
std::cout << "key: " << pair.first << ", value: " << pair.second << std::endl;
}
return 0;
}
结构化绑定遍历(c++17及以上)
c++17新增了结构化绑定特性,遍历unordered_map时可以直接将键值对拆分为独立的变量,不需要再通过first和second访问,代码更直观。
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<int, std::string> my_map;
my_map[1] = "apple";
my_map[2] = "banana";
my_map[3] = "orange";
// 结构化绑定遍历,直接获取key和value
for (const auto& [key, value] : my_map) {
std::cout << "key: " << key << ", value: " << value << std::endl;
}
return 0;
}
不同遍历方式的对比
下面通过表格对比几种遍历方式的特点,方便开发者选择:
| 遍历方式 | 适用c++版本 | 代码简洁度 | 特点 |
|---|---|---|---|
| 迭代器遍历 | c++11之前及之后 | 一般 | 兼容性好,支持修改遍历过程中的迭代器位置 |
| 范围for循环 | c++11及以上 | 较高 | 代码简洁,不需要手动操作迭代器 |
| 结构化绑定遍历 | c++17及以上 | 最高 | 直接拆分键值对,可读性最强 |
遍历注意事项
- unordered_map遍历时元素的顺序是不确定的,因为它是无序容器,遍历顺序和插入顺序没有关联。
- 遍历过程中如果需要删除元素,使用迭代器遍历时可以通过erase方法返回下一个有效迭代器,避免迭代器失效。
- 如果不需要修改元素内容,建议使用const引用接收遍历到的元素,减少不必要的拷贝开销。
注意:unordered_map的键是const类型,遍历过程中不能修改键的值,否则会破坏哈希表的结构,只能修改对应的值。
unordered_map遍历c++迭代器范围for循环修改时间:2026-07-02 23:45:23