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

C++ map multimap 容器:赋值、排序、大小与删除操作

概述

mapmultimap是C++ STL中的关联容器,它们存储的是键值对(key-value pairs),并且会根据键(key)自动排序。两者的主要区别在于:

  • map不允许重复的键
  • multimap允许重复的键

本文将详细解析示例代码中涉及的map操作,包括赋值排序大小查询删除等核心功能。

1. 头文件与命名空间

#include <iostream>
#include <map>using namespace std;
  • #include <map>:必须包含的头文件,提供mapmultimap的实现
  • using namespace std:使用标准命名空间,避免每次都要写std::

2. 自定义排序规则(仿函数)

class CompareInt {
public:bool operator()(const int& left, const int& right) const {return left > right;  // 降序排序}
};
  • 仿函数(Functor):重载了()运算符的类,可以像函数一样调用
  • 这里实现了降序排序规则,当left > right时返回true
  • 注意operator()应该声明为const,因为它不修改对象状态

3. map的声明与初始化

map<int, string> mapStu;  // 默认less 升序排序
//map<int, string,greater<int>> mapStu;  // greater 降序排序
//map<int, string,CompareInt> mapStu;  // 使用自定义仿函数
  • 默认排序:不指定第三个模板参数时,使用less<Key>,即升序排序
  • 内置排序规则:可以使用greater<Key>实现降序排序
  • 自定义排序:通过传递自定义的仿函数类型作为第三个模板参数

4. 插入元素

mapStu.insert(pair<int, string>(2, "小明"));
mapStu.insert(pair<int, string>(3, "廉颇"));
mapStu.insert(pair<int, string>(1, "妲己"));
mapStu.insert(pair<int, string>(4, "庄周"));
  • insert():插入键值对
  • 使用pair构造键值对,first是键,second是值
  • 插入后元素会根据键自动排序

5. 拷贝构造与赋值

map<int, string> mapB(mapStu);   // 拷贝构造
map<int, string> mapC = mapStu;  // 赋值操作
  • 拷贝构造:创建一个新map并复制所有元素
  • 赋值操作:将已有map的所有元素复制到另一个map
  • 两种方式都会创建与原map完全相同的新容器

6. 元素访问与修改

mapC[3] = "小乔";  // 通过键访问并修改值
  • operator[]:通过键访问对应的值
  • 如果键不存在,会自动插入该键,值为默认构造

7. 交换操作

mapC.swap(mapB);  // 交换两个map的内容
  • swap():高效交换两个map的内容
  • 实际只交换内部指针,不复制元素,时间复杂度O(1)

8. 删除操作

8.1 删除区间元素
map<int, string>::iterator iBegin = mapB.begin();
++iBegin;
map<int, string>::iterator iEnd = mapB.end();
mapB.erase(iBegin, iEnd);  // 删除[iBegin, iEnd)区间
  • erase(beg, end):删除迭代器区间[beg, end)内的元素
  • 区间是半闭半开的,包含beg但不包含end
  • 返回void(新标准返回下一个元素的迭代器)
8.2 删除单个元素
mapC.erase(mapC.begin());  // 删除第一个元素
mapC.erase(4);             // 删除键为4的元素
  • erase(pos):删除迭代器pos指向的元素
  • erase(key):删除所有键等于key的元素(对于map最多一个)
8.3 清空容器
mapC.clear();  // 清空所有元素
  • clear():删除容器中的所有元素,使size为0
8.4 删除结果检查
map<int, string, greater<int>>::size_type st = mapStu.erase(5);
cout << "st = " << st << endl;  // 输出删除的元素个数
  • **erase(key)**返回删除的元素个数
  • 对于map,返回值只能是0或1
  • 对于multimap,返回值可以是任意非负整数

9. 大小查询

if (!mapC.empty()) {cout << "mapC的大小: " << mapC.size() << endl;
}
  • empty():检查容器是否为空
  • size():返回容器中元素的个数
  • 通常先检查empty()再调用size()更安全

10. 迭代器遍历

for (map<int, string, CompareInt>::iterator it = mapStu.begin(); it != mapStu.end(); it++) {cout << "key: " << (*it).first << "  value: " << (*it).second << endl;
}
  • begin()/end():获取首元素和尾后迭代器
  • 迭代器解引用得到pair<const Key, Value>
  • 可以用it->firstit->second访问键和值

完整代码回顾

#include <iostream>
#include <map>using namespace std;// 仿函数用于比较int(降序排序)
class CompareInt {
public:bool operator()(const int& left, const int& right) const {return left > right;    // 降序排序}
};int main(void) {map<int, string> mapStu;  // 默认less 升序排序//map<int, string,greater<int>> mapStu;  // greater 降序排序// 使用自定义的仿函数作为比较器//map<int, string,CompareInt> mapStu;  mapStu.insert(pair<int, string>(2, "小明"));mapStu.insert(pair<int, string>(3, "廉颇"));mapStu.insert(pair<int, string>(1, "妲己"));mapStu.insert(pair<int, string>(4, "庄周"));// map对象的拷贝构造与赋值map<int, string> mapB(mapStu);   // 拷贝构造for (map<int, string>::iterator it = mapB.begin(); it != mapB.end(); it++) {cout << "key: " << (*it).first << "  value: " << (*it).second << endl;}cout << endl;map<int, string> mapC = mapStu;  // 赋值for (map<int, string>::iterator it = mapC.begin(); it != mapC.end(); it++) {cout << "key: " << (*it).first << "  value: " << (*it).second << endl;}cout << endl;mapC[3] = "小乔";mapC.swap(mapB);// map的删除map<int, string>::iterator iBegin = mapB.begin();++iBegin;map<int, string>::iterator iEnd = mapB.end();mapB.erase(iBegin, iEnd);  // 删除区间mapC.erase(mapC.begin());  // 删除第一个元素mapC.erase(4);             // 删除key为4的元素mapC.clear();              // 清空容器map<int, string, greater<int>>::size_type st = mapStu.erase(5);cout << "st = " << st << endl;  // 输出删除个数// map的大小if (!mapC.empty()) {cout << "mapC的大小: " << mapC.size() << endl;}// 遍历mapfor (map<int, string, CompareInt>::iterator it = mapStu.begin(); it != mapStu.end(); it++) {cout << "key: " << (*it).first << "  value: " << (*it).second << endl;}system("pause");return 0;
}

相关文章:

  • axios的基本使用
  • 深入了解linux系统—— 基础IO(下)
  • VS Code 开启mcp控制本地的redis
  • iOS 初识RunLoop
  • 深度学习推理引擎---ONNX Runtime
  • Vue+Go 自定义打字素材的打字网站
  • 海盗王改60帧时有关树木抖动的问题
  • Leetcode 3551. Minimum Swaps to Sort by Digit Sum
  • Protect Your Digital Privacy: Obfuscate, Don’t Hide
  • C语言指针深入详解(二):const修饰指针、野指针、assert断言、指针的使用和传址调用
  • 用 UniApp 构建习惯打卡 App —— HabitLoop 开发记
  • 报告精读:华为2024年知行合一通信行业数据治理实践指南报告【附全文阅读】
  • leetcodehot100刷题——排序算法总结
  • python中http.cookiejar和http.cookie的区别
  • React 19版本refs也支持清理函数了。
  • 【每天一个知识点】湖仓一体(Data Lakehouse)
  • 规则联动引擎GoRules初探
  • 牛客网NC21989:牛牛学取余
  • 新电脑软件配置二:安装python,git, pycharm
  • UnLua源码分析(一)初始化流程
  • 国际观察丨美中东政策生变,以色列面临艰难选择
  • 从《缶翁的世界》开始,看吴昌硕等湖州籍书画家对海派的影响
  • 中国首颗地质行业小卫星“浙地一号”成功发射
  • 定制基因编辑疗法治愈罕见遗传病患儿
  • 深圳南澳码头工程环评将再次举行听证会,项目与珊瑚最近距离仅80米
  • 证监会:2024年依法从严查办证券期货违法案件739件,作出处罚决定592件、同比增10%