#P1864. map的用法
map的用法
Description
在 C++ 中,`std::map` 是标准模板库(STL)中的一个**关联容器**,用于存储**键值对(key-value pairs)**,并且每个键都是唯一的。🧩 一、基本概念
✅ 特点:
- 存储的元素是
pair<const Key, T>类型(即键值对) - 按键自动排序(默认升序)
- 键唯一,不能重复
- 内部实现为红黑树
- 插入、查找、删除的时间复杂度为:
O(log n)
📦 二、头文件
#include <map>
🛠 三、基本用法
1. 定义 map
map<string, int> age;
map<int, string> m;
// 自定义比较函数(降序)
map<int, string, greater<int>> m_desc;
2. 插入元素
age["Alice"] = 25;
age.insert(make_pair("Bob", 30));
age.insert({"Charlie", 28});
// 使用 value_type 插入
m.insert(map<int, string>::value_type(1, "one"));
⚠️ 如果键已存在,使用
[]会覆盖旧值;insert()不会插入重复键。
3. 查找元素
if (age.find("Alice") != age.end()) {
cout << "Alice's age: " << age["Alice"] << endl;
}
4. 遍历 map
for (auto it = age.begin(); it != age.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
// C++11 范围 for 循环
for (const auto& pair : age) {
cout << pair.first << ": " << pair.second << endl;
}
5. 删除元素
age.erase("Alice"); // 按 key 删除
age.erase(it); // 按迭代器删除
age.erase(age.begin(), age.end()); // 删除范围
6. 其他常用操作
cout << "Size: " << age.size() << endl;
cout << "Empty? " << age.empty() << endl;
age.clear();
🔍 四、常用函数总结
| 函数 | 说明 |
|---|---|
insert(pair) |
插入键值对 |
operator[key] |
访问/插入指定键的值(若不存在则创建默认值) |
find(key) |
查找键是否存在 |
count(key) |
返回键出现次数(只能是 0 或 1) |
erase(key) / erase(it) |
删除键或迭代器指向的元素 |
clear() |
清空所有元素 |
size() |
返回元素个数 |
empty() |
判断是否为空 |
🧪 五、示例代码
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> ages;
// 插入数据
ages["Alice"] = 25;
ages["Bob"] = 30;
ages.insert({"Charlie", 28});
// 修改已有值
ages["Alice"] = 26;
// 查找并输出
if (ages.find("Alice") != ages.end()) {
cout << "Alice: " << ages["Alice"] << endl;
}
// 遍历
for (const auto& pair : ages) {
cout << pair.first << " -> " << pair.second << endl;
}
// 删除
ages.erase("Bob");
return 0;
}
🔄 六、自定义比较函数(高级)
struct cmp {
bool operator()(const int a, const int b) const {
return a > b; // 降序排列
}
};
map<int, string, cmp> m;
m[3] = "three";
m[1] = "one";
m[2] = "two";
for (auto p : m) {
cout << p.first << " -> " << p.second << endl;
}
// 输出:
// 3 -> three
// 2 -> two
// 1 -> one
💡 七、应用场景
- 存储键值对数据,如字典、电话簿、配置信息等
- 快速查找某个键对应的值
- 实现频率统计、索引结构等
- 需要有序遍历时使用
🆚 与 unordered_map 的区别
| 特性 | map |
unordered_map |
|---|---|---|
| 底层实现 | 红黑树 | 哈希表 |
| 是否有序 | 是 | 否 |
| 插入/查找时间复杂度 | O(log n) | 平均 O(1),最坏 O(n) |
| 是否支持自定义哈希函数 | ❌ | ✅ |
| 是否支持范围查询(lower_bound) | ✅ | ❌ |
如果你需要 unordered_map 或 multimap 的详细讲解,也可以告诉我!