C++ map

一、什么是 map

map 是 C++ 标准库中的关联式容器,用于存储 键值对(Key-Value) ,底层基于 红黑树 实现。其核心特性包括:

  • 键唯一性:每个键(Key)在容器中唯一,不可重复。

  • 自动排序:键值对按键的升序排列。

  • 高效查找 :插入、删除、查找的时间复杂度为 O(logN)

    cpp 复制代码
    #include <map>
    std::map<std::string, int> ageMap;
    ageMap["Alice"] = 25;  
    ageMap["Bob"] = 30;

    二、基本操作与示例

    1. 插入元素

  • insert:支持插入单个元素或范围。

  • 直接赋

    cpp 复制代码
    std::map<int, std::string> m;
    m.insert({1, "Apple"});      // 插入单个元素
    m.insert({{2, "Banana"}, {3, "Cherry"}});  // 插入多个元素
    m[4] = "Date";               // 使用下标插入

    :通过 [] 操作符直接赋值(若键不存在则自动创建)。

2. 查找元素

  • find :返回指向键的迭代器,若未找到则返回 end()

  • count :判断键是否存在(返回 0 或 1)。

    cpp 复制代码
    auto it = m.find(2);
    if (it != m.end()) {
        std::cout << it->second;  // 输出 "Banana"
    }

    3. 删除元素

  • erase:支持按键删除或按迭代器删除

cpp 复制代码
m.erase(2);           // 删除键为 2 的元素
m.erase(it);          // 删除迭代器指向的元素

三、进阶用法

1. 自定义键类型

默认使用 less<Key> 进行键比较,若需自定义排序规则,可通过仿函数或 operator< 实现。

cpp 复制代码
struct Person {
    std::string name;
    int age;
    bool operator<(const Person& p) const {
        return age < p.age;  // 按年龄排序
    }
};
std::map<Person, std::string> customMap;

2. 高效插入(C++17+)

  • try_emplace :避免不必要的临时对象构造。

    cpp 复制代码
    std::map<std::string, std::string> m;
    m.try_emplace("key", "value");  // 类似 insert,但更高效

    3. 内存优化技巧

  • 预分配策略:对于有序数据,提前排序后批量插入可减少红黑树旋转开销。

  • 节点转移 :使用 extract() 在容器间转移节点。

cpp 复制代码
auto node = m.extract("key");  // 提取节点
node.key() = "new_key";        // 修改键(需保证新键不冲突)
m.insert(std::move(node));     // 插入回容器

常见问题

  1. 键不可修改:键的值在插入后不可更改(否则破坏红黑树结构)。
  2. 避免重复键 :插入重复键时,insert 会失败,但 [] 会覆盖旧值。
  3. 并发安全 :多线程环境下需自行加锁(map 非线程安全)。
相关推荐
端平入洛20 小时前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054963 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月3 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js