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

C++学习笔记(三十一)——map

一、std::map

(1)map与其适用场景

std::map 是 C++的STL(标准模板库)中的关联容器(Associative Container),底层基于 红黑树(Red-Black Tree) 实现,支持键值对存储,键自动排序,并提供高效的查找、插入和删除操作

特点:

  • 键值对存储:每个元素是 key-value 形式,如 {1, "Alice"}
  • 键唯一:不允许重复键(使用 std::multimap 可允许重复键)。
  • 自动排序:键按升序存储(可自定义降序)。
  • 底层实现:基于红黑树(Red-Black Tree)inserterasefind 复杂度为 O(log n)
  • 支持随机访问:可通过 operator[] 访问或修改值。

适用场景:

  • 字典存储(Key-Value 映射)(如学生成绩表)。
  • 高效查找(比 vectorlist 快)
  • 按键自动排序(如排名表)。

(2)map vs unordered_map

特性map(有序映射)unordered_map(哈希映射)
底层实现红黑树哈希表
时间复杂度O(log n)O(1)(最坏 O(n)
是否排序自动排序无序
适用场景有序存储,适用于范围查询更快的查找(无序)

二、std::map 的常用函数

函数作用
insert({key, value})插入元素(如果 key 存在,不会修改)
erase(key)删除指定键的元素
find(key)查找键,返回迭代器
count(key)检查键是否存在(返回 01
operator[]访问/修改元素
size()获取元素个数
empty()判断是否为空
clear()清空 map

三、std::map的基本使用

(1) 插入、访问与遍历

示例:

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

int main() {
    map<int, string> students;

    students.insert({ 1, "Alice" });
    students.insert({ 3, "Charlie" });
    students[2] = "Bob"; // 另一种插入方式

    cout << "学生名单:" << endl;
    for (const auto s : students)
    {
        cout << "ID: " << s.first << ", Name: " << s.second << endl;
    }

    system("pause");
    return 0;
}

注意:

  • insert函数的返回值是pair<iterator, bool>,第一个参数是插入元素或已有键对应的迭代器,第二个参数表示是否成功插入元素
  • 执行插入操作时,首先检查给定键是否已存在于map,如果键已存在于map,则它不会插入map,并且迭代器将迭代到现有键返回,否则在map中插入新元素。

(2) 查找键

示例:

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

int main() {
    map<int, string> students = { {1, "Alice"}, {2, "Bob"}, {3, "Charlie"} };

    if (students.find(2) != students.end())
    {
        cout << "找到 ID 2: " << students[2] << endl;
    }
    else
    {
        cout << "ID 2 不存在" << endl;
    }
        
    system("pause");
    return 0;
}

注意:

  • find(key)—— 查找键,返回迭代器:若存在,返回指向目标键的迭代器;若不存在,返回map.end()迭代器

(3) 删除元素

示例:

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

int main() {
    map<int, string> students = { {1, "Alice"}, {2, "Bob"}, {3, "Charlie"} };

    students.erase(2); // 删除 ID=2 的学生

    for (const auto& s : students)
    {
        cout << "ID: " << s.first << ", Name: " << s.second << endl;
    }
    
    system("pause");
    return 0;
}

(4) 自定义排序(降序)

示例:

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

int main() {
    map<int, string, greater<int>> students = { {1, "Alice"}, {2, "Bob"}, {3, "Charlie"} };

    for (const auto& s : students)
    {
        cout << "ID: " << s.first << ", Name: " << s.second << endl;
    }
    
    system("pause");
    return 0;
}

注意:

  • map默认排序为升序set<int> s),可用 std::greater<> 降序排序

四、std::map的应用

(1) 统计单词出现次数

示例:

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

int main() {
    map<string, int> wordCount;
    string text = "apple banana apple orange banana apple";

    stringstream ss(text);
    string word;
    while (ss >> word)
    {
        wordCount[word]++;
    }   

    for (const auto& w : wordCount)
    {
        cout << w.first << ": " << w.second << endl;
    }
        
    system("pause");
    return 0;
}

注意:

  • <sstream>是C++ 标准库中的一个组件,它提供了一种方便的方式来处理字符串流(可以像处理流一样处理字符串)。
  • stringstream是一个流类,允许你将字符串当作输入/输出流来使用,这使得从字符串中读取数据或将数据写入字符串变得非常简单。

(2) 排行榜(按分数排序)

示例:

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

int main() {
    map<int, string, greater<int>> ranking;

    ranking[95] = "Alice";
    ranking[90] = "Bob";
    ranking[100] = "Charlie";

    for (const auto& r : ranking)
    {
        cout << r.first << " 得分: " << r.second << endl;
    }

    system("pause");
    return 0;
}
http://www.dtcms.com/a/108344.html

相关文章:

  • Git的基础使用方法
  • 微信小程序唤起app
  • 【Docker】使用Docker快速部署n8n和unclecode/crawl4ai
  • PEFT实战(一)——LoRA
  • 大模型学习一:deepseek api 调用实战以及参数介绍
  • 【动手学深度学习】#7 现代卷积神经网络
  • C++多态:从青铜九鼎到虚函数表的千年演化密码
  • Pytorch|RNN-心脏病预测
  • 文件分享系统--使用AI Trae开发前后端
  • 鸿蒙应用元服务开发-Account Kit获取华为账号用户信息概述
  • 魔塔社区使用llamafactory微调AI阅卷试题系统
  • 应用弥散张量成像和支持向量机检测慢性爆炸相关轻度颅脑损伤
  • Dockerfile文件构建镜像Anaconda+Python教程
  • 六十天Linux从0到项目搭建(第十八十九天)(缓冲区机制、未打开的磁盘存放、文件存储、磁盘物理结构、寻址、块设备管理、文件系统、增删查改、硬链接、软链接)
  • 通俗易懂的解释Git操作中“合并”和“变基”的区别
  • CMD命令通过已知ip使用以下三种方式来获取对方主机名
  • 常见优化SQL语句策略和示例
  • ControlNet-Tile详解
  • 最新Spring Security实战教程(八)Remember-Me实现原理 - 持久化令牌与安全存储方案
  • Python数据可视化-第3章-图表辅助元素的定制
  • PyTorch 中池化层MaxPool2d
  • CSS--解决float: right在空间不够时会自动往下移的问题
  • 音视频入门基础:MPEG2-TS专题(26)——通过FFmpeg命令使用RTP发送TS流
  • 【Word】批注一键导出:VBA 宏
  • C#核心学习(五)面向对象--封装(4)C#中的索引器详解:让对象像数组一样灵活访问
  • MySQL的数据目录以及日志
  • 企业网络优化方案:SD-WAN赋能企业远程办公
  • 使用JSON.stringify报错:Uncaught TypeError: cyclic object value
  • RNN模型与NLP应用——(6/9)Text Generation(文本自动生成)
  • UE小:在Unreal Engine 5中实现多层静态网格体遮挡拾取