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

概述

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

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

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

1. 头文件与命名空间

cpp 复制代码
#include <iostream>
#include <map>

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

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

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

3. map的声明与初始化

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

4. 插入元素

cpp 复制代码
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. 拷贝构造与赋值

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

6. 元素访问与修改

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

7. 交换操作

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

8. 删除操作

8.1 删除区间元素
cpp 复制代码
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 删除单个元素
cpp 复制代码
mapC.erase(mapC.begin());  // 删除第一个元素
mapC.erase(4);             // 删除键为4的元素
  • erase(pos) :删除迭代器pos指向的元素
  • erase(key) :删除所有键等于key的元素(对于map最多一个)
8.3 清空容器
cpp 复制代码
mapC.clear();  // 清空所有元素
  • clear():删除容器中的所有元素,使size为0
8.4 删除结果检查
cpp 复制代码
map<int, string, greater<int>>::size_type st = mapStu.erase(5);
cout << "st = " << st << endl;  // 输出删除的元素个数
  • **erase(key)**返回删除的元素个数
  • 对于map,返回值只能是0或1
  • 对于multimap,返回值可以是任意非负整数

9. 大小查询

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

10. 迭代器遍历

cpp 复制代码
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->first和it->second访问键和值

完整代码回顾

cpp 复制代码
#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;
    }

    // 遍历map
    for (map<int, string, CompareInt>::iterator it = mapStu.begin(); 
         it != mapStu.end(); it++) {
        cout << "key: " << (*it).first << "  value: " << (*it).second << endl;
    }

    system("pause");
    return 0;
}
相关推荐
阿俊-全栈开发3 小时前
LikeShop 单商户SaaS商城分销模块二开:佣金计算与结算逻辑实现
java·开发语言·微服务·likeshop·likeshop开源商城·likeshop多商户
weixin_424183615 小时前
开放—封闭原则实战(下):基于策略的流程编排与编译期多态
c++·分布式·系统架构
wuminyu6 小时前
C++协程实现接收端的零拷贝Buffer管理原理剖析
java·linux·c语言·jvm·c++
m0_380743876 小时前
C++中的freopen的用法实例详解
开发语言·c++
Escalating_xu6 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
jimy17 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743877 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php
朝朝辞暮i7 小时前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法
小凡geo7 小时前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
朝朝辞暮i8 小时前
C++ 第 4 课:if / else —— 让程序自己做决定
开发语言·c++