C++ std::map
1. 什么是 std::map?
std::map 是 C++ 标准库提供的一种关联容器,它基于红黑树实现,可以存储键值对(key-value pairs)。map 中的元素根据键的大小自动排序,且每个键在 map 中是唯一的。
2. std::map 的特点
- 自动排序:
map会根据键(key)进行自动排序,默认为升序排列。 - 唯一键:每个键值在 
map中是唯一的,不能重复。 - 高效查找:
map采用平衡二叉搜索树(如红黑树)实现,因此支持高效的插入、删除和查找操作,平均时间复杂度为 O(log n)。 - 元素类型:
map中的元素类型是std::pair<const Key, T>,即键和值分别为Key类型和T类型,键是不可修改的。 
3. std::map 常用操作
| 操作 | 描述 | 
|---|---|
insert() | 
插入元素,如果键已经存在,则不会插入新的键值对。 | 
find() | 
查找指定键的元素,返回一个迭代器,若找不到则返回 end()。 | 
count() | 
查找指定键是否存在,返回键出现的次数(对于 map 来说,一般为 0 或 1)。 | 
lower_bound() | 
返回指向第一个 不小于 指定键的元素的迭代器。 | 
upper_bound() | 
返回指向第一个 大于 指定键的元素的迭代器。 | 
erase() | 
删除指定键的元素,或者删除指定范围内的元素。 | 
size() | 
返回 map 中元素的数量。 | 
empty() | 
检查 map 是否为空。 | 
4. std::map 示例代码
#include <iostream>#include <map>using namespace std;int main() {// 创建一个 map,键为字符串,值为整数map<string, int> ma;// 插入元素ma["apple"] = 1;ma["banana"] = 2;ma["lemon"] = 3;// 输出 map 的大小cout << "Size of map: " << ma.size() << endl;// 查找并输出键 "apple" 的值cout << "Value of apple: " << ma["apple"] << endl;// 检查键 "pear" 是否存在if (ma.count("pear")) {cout << "pear exists" << endl;} else {cout << "pear does not exist" << endl;}// 使用 lower_bound 查找不小于 "cow" 的第一个元素auto it = ma.lower_bound("cow");if (it != ma.end()) {cout << "Lower bound of cow: " << it->first << " -> " << it->second << endl;} else {cout << "No element greater than or equal to cow" << endl;}// 遍历 map 并输出每个键值对for (const auto& pair : ma) {cout << pair.first << " -> " << pair.second << endl;}// 删除键为 "banana" 的元素ma.erase("banana");// 输出删除后的 mapcout << "After erase:" << endl;for (const auto& pair : ma) {cout << pair.first << " -> " << pair.second << endl;}return 0;}
5. 代码解析
插入元素:
ma["apple"] = 1;ma["banana"] = 2;ma["lemon"] = 3;
使用
map的[]操作符可以插入或修改元素。如果指定的键不存在,会插入新的键值对;如果键已经存在,会更新对应的值。查找元素:
if (ma.count("pear")) {cout << "pear exists" << endl;} else {cout << "pear does not exist" << endl;}
使用
count来检查一个键是否存在。对于map,count返回值要么是 0(不存在),要么是 1(存在)。使用
lower_bound查找第一个不小于给定键的元素:auto it = ma.lower_bound("cow");if (it != ma.end()) {cout << "Lower bound of cow: " << it->first << " -> " << it->second << endl;}
lower_bound("cow")会返回一个指向第一个键不小于"cow"的元素的迭代器。在这里,返回的是"lemon"。遍历
map:for (const auto& pair : ma) {cout << pair.first << " -> " << pair.second << endl;}
使用范围基
for循环遍历map,可以通过pair.first获取键,pair.second获取值。删除元素:
ma.erase("banana");
使用
erase删除指定键的元素,删除后该元素不再存在于map中。
6. 小结
std::map是一个有序的关联容器,键值对按照键的顺序自动排列。- 常用操作包括插入、查找、删除、遍历以及查找指定位置的元素(如使用 
lower_bound和upper_bound)。 map提供了高效的查找和插入操作,适用于需要按键排序存储数据的场景。
