Below you will find pages that utilize the taxonomy term “Algorithm"”
February 13, 2025
unordered_map
unordered_map | unordered_set | |
|---|---|---|
| 存储内容 | 键值对 (std::pair<const Key, T>) | 仅存储键 (Key) |
| 是否允许重复键 | 键唯一(重复键会覆盖) | 键唯一(重复插入无效) |
| 主要用途 | 快速通过键查找值 | 快速判断键是否存在 |
| 典型操作 | map[key] = value、map.find(key) | set.insert(key)、set.count(key) |
| 内存占用 | 更高(需存储键和值) | 更低(仅存储键) |
1. 创建 unordered_map 对象
#include <unordered_map>
#include <string>
int main() {
// 默认构造函数
std::unordered_map<std::string, int> map1;
// 初始化列表构造函数
std::unordered_map<std::string, int> map2 = {{"apple", 1}, {"banana", 2}};
// 拷贝构造函数
std::unordered_map<std::string, int> map3(map2);
return 0;
}
2. 插入
insert插入一个键值对
map1.insert({"orange", 3}); map1.insert(std::make_pair("grape", 4));operator[]通过键插入或访问值。如果键不存在,会插入一个默认值。
map1["apple"] = 10; // 插入或修改 int value = map1["apple"]; // 访问
3. 访问元素
at访问指定键的值,如果键不存在会抛出
std::out_of_range异常。int value = map1.at("apple");operator[]访问或插入指定键的值。
int value = map1["apple"];