当前位置: 首页 > news >正文

C++stl map容器详解

C++map容器详解

求关注

一、Map容器概述
map是C++标准模板库(STL)中的关联式容器,以键值对(Key-Value)形式存储数据,底层通过红黑树(一种自平衡二叉搜索树)实现。其核心特性包括:

  1. 自动排序:元素按Key的升序排列,无需手动排序。

  2. 唯一键值:每个Key在容器中唯一,若重复插入则覆盖或忽略(取决于插入方式)。

  3. 高效操作:插入、删除、查找的时间复杂度为O(log n),适合频繁查找的场景。

示例:定义map

C++

#include <map>
#include <string>
using namespace std;

map<int, string> studentMap;  // Key为int类型,Value为string类型

二、Map核心操作

1. 插入数据

三种常用插入方式

  • insert()函数:安全插入,若Key已存在则不会覆盖。

    C++

    studentMap.insert(pair<int, string>(101, "Alice"));
    studentMap.insert(map<int, string>::value_type(102, "Bob"));
    studentMap.insert(make_pair(103, "Charlie"));  // 推荐简洁写法
  • 数组[]操作符:若Key存在则覆盖Value。

    C++

    studentMap[104] = "David";  // 若104不存在则插入,存在则更新
  • 返回值判断:通过pair<iterator, bool>检查插入是否成功37。

    C++

    复制

    auto result = studentMap.insert(make_pair(101, "Eve"));
    if (!result.second) cout << "Key 101已存在!";

2. 查找与访问

  • find()函数:返回迭代器,未找到时指向end()14。

    C++

    auto it = studentMap.find(102);
    if (it != studentMap.end()) 
        cout << "找到:" << it->second;  // 输出Bob
  • count()函数:返回Key是否存在(0或1)。

  • lower_bound()upper_bound():用于范围查找。

3. 删除数据

  • 按Key删除erase(key)

  • 按迭代器删除erase(iterator)

  • 范围删除erase(start_iterator, end_iterator)

    C++

    studentMap.erase(103);  // 删除Key为103的元素
    auto it = studentMap.find(104);
    if (it != studentMap.end()) studentMap.erase(it);

4. 遍历元素

  • 迭代器遍历

    C++

    for (auto it = studentMap.begin(); it != studentMap.end(); ++it) 
        cout << it->first << ": " << it->second << endl;
  • C++11范围循环

    C++

    for (auto& entry : studentMap) 
        cout << entry.first << ": " << entry.second << endl;

三、高级技巧与注意事项

1. 自定义排序规则

默认按Key升序排列,若需自定义排序,可提供比较函数:

C++

复制

struct CompareDesc {
    bool operator()(const int& a, const int& b) const {
        return a > b;  // 降序排列
    }
};
map<int, string, CompareDesc> customMap;

2. 性能优化

  • 避免频繁插入删除:红黑树结构调整有开销。

  • 预分配空间:若已知元素数量,可提前预留内存。

3. 常见问题

  • 迭代器失效:删除元素时需注意,正确写法为erase(it++)

  • 键不可修改:Key为常量,需先删除旧键再插入新键。


四、应用实例

案例:统计单词频率

C++

复制

map<string, int> wordCount;
string word;
while (cin >> word) 
    wordCount[word]++;  // 自动初始化并统计

for (auto& entry : wordCount) 
    cout << entry.first << ": " << entry.second << "次" << endl;

五、总结

map容器凭借其高效的查找能力和自动排序特性,广泛应用于数据映射、缓存管理、配置存储等场景。掌握其核心操作与底层原理,能显著提升代码效率。对于需要更高插入/删除性能的场景,可考虑unordered_map(哈希表实现)。

相关文章:

  • openHalo:国产开源数据库新力量
  • HCIP【BGP协议(详解)】
  • 搜索与图论 树的深度优先遍历 树的重心
  • Windows 权限配置文件解析与安全分析(GPP,GPO,LSA)
  • 查询当前用户的购物车和清空购物车
  • 57.基于springboot和vue校园跑腿服务平台
  • CSS语言的硬件驱动
  • 第五讲(上) | string类的使用
  • Linux | 安装超级终端串口软件连接i.MX6ULL开发板(8)
  • Git 从入门到精通(开源协作特别版)
  • Windows安装Node.js+Express+Nodemon
  • 6.1 宽度优先搜索算法(BFS)
  • 1.Qt信号与槽
  • 如何删除Debian中的用户?删除Debian用户方法
  • 网络响应速度慢,应该用什么办法来定位问题?
  • WebUI问题总结
  • [dp4_路径问题] 下降路径最小和 | 最小路径和 | 地下城游戏
  • vscode报Module containing this breakpoint has not yet loaded
  • 【GPT入门】第33 课 一文吃透 LangChain:chain 结合 with_fallbacks ([]) 的实战指南
  • Oracle数据库数据编程SQL<6.1 数据字典表查询大全>
  • wordpress 在线demo/搜索引擎优化名词解释
  • 湖南网站建设制作/网站都有哪些
  • 北京网站建设费用/百度网站推广申请
  • 如何查看网站服务器类型/怎样做网站平台
  • 潍坊建设网站的公司/推广活动策划方案范文
  • 做袜子娃娃的网站/爱站网关键词