一、map容器的定义和性质
1.map容器的定义
map是一种基于红黑树的关联式容器,用于存储键值对(key-value pairs),存储的都是pair对象,其中的元素是按照键的顺序自动排序的,这使得它非常适合需要快速查找和有序数据的场景。
2.map容器的性质
- 键值对:
map存储的是键值对,其中每个键都是唯一的。 - 排序:
map中的元素按照键的顺序自动排序,通常是升序。 - 唯一性:每个键在
map中只能出现一次。 - 双向迭代器:
map提供了双向迭代器,可以向前和向后遍历元素。
二、map容器的使用
1.map容器的声明
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<string, int> mp;
mp["Alice"] = 30;
mp["Bob"] = 25;
mp["Charlie"] = 35;
for (auto it = mp.begin(); it != mp.end(); ++it)
{
cout << it->first << " is " << it->second << " years old." << std::endl;
}
return 0;
}
输出结果为:
Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.
2.map容器的基础操作
| 常见成员函数 | 作用 | 时间复杂度 |
|---|---|---|
| insert({key, value}) | 向 map 中插入一个键-值对 <key,value> | O(log n) |
| emplace({key, value}) | 直接向 map 中插入一个键-值对 <key,value>,效率更高 | O(log n) |
| erase(key) | 删除 map 中指定的键-值对 | O(log n) |
| find(key) | 查找 map 中指定键对应的键-值对的迭代器 | O(log n) |
| operator[key] | 查找 map 中指定键对应的值 | O(log n) |
| count(key) | 查找 map 中键的数量,由于键是唯一的,故只返回 0 或 1 | O(log n) |
| size() | 返回 map 中键-值对的数量 | O(1) |
| clear() | 清空 map 中的所有键-值对 | O(n) |
| empty() | 判断 map 是否为空 | O(1) |
| begin() | 返回 map 中第一个键-值对的迭代器 | O(1) |
| end() | 返回 map 中最后一个键-值对的下一个迭代器 | O(1) |
在执行取值运算([] 运算符)时,必须确保键存在,否则可能产生错误,可以通过以下方法保证安全:
map<int, int> mp; // map 的声明
// 方法一:通过 find() 函数判断,返回键-值对的迭代器;如果未找到,返回 end()
if (mp.find(key) != mp.end()) {
cout << mp[key] << '\n';
}
// 方法二:通过 count 判断键是否存在,推荐
if (mp.count(key)) {
cout << mp[key] << '\n';
}
遍历map容器中所有的键-值对有以下两种方法:
map<int, int> mp;
// 方法一:使用 auto 关键字进行遍历(推荐)
for (auto &i : mp) {
cout << i.first << " " << i.second << '\n';
}
// 方法二:使用迭代器进行遍历(不推荐)
for (map<int, int>::iterator it = mp.begin(); it != mp.end(); ++it) {
cout << it->first << " " << it->second << '\n';
}


