一、std::map 的特点
- 基于红黑树实现:内部元素有序排列,按照 key 自动升序(默认使用
< 比较)。
- 每个 key 唯一,key-value 形式存储。
- 查找、插入、删除时间复杂度为 O(log n)。
- 元素按键排序,可自定义比较器(如降序)。
- 可通过
operator[] 访问 / 插入元素(非 const map)。
- 支持完整迭代器功能,可用范围、反向、常量迭代器等。
二、初始化方式
🔹1. 默认构造
std::map<int, std::string> m;
🔹2. 列表初始化(C++11)
std::map<int, std::string> m = {
{1, "one"},
{2, "two"},
{3, "three"}
};
🔹3. 区间构造
std::vector<std::pair<int, std::string>> v = {{1, "A"}, {2, "B"}};
std::map<int, std::string> m(v.begin(), v.end());
🔹4. 拷贝/移动构造
std::map<int, std::string> m1 = {{1, "A"}};
std::map<int, std::string> m2(m1); // 拷贝构造
std::map<int, std::string> m3(std::move(m1)); // 移动构造