「C/C++」C++ STL容器库 之 std::map 键值容器类

✨博客主页
何曾参静谧的博客
「C/C++」C/C++程序设计
「VS」Visual Studio 「C/C++」C/C++程序设计 「UG/NX」BlockUI集合
「Win」Windows程序设计 「DSA」数据结构与算法 「UG/NX」NX二次开发
「QT」QT5程序设计 「File」数据文件格式 「PK」Parasolid函数说明
「Math」探秘数学世界

目录

std::map 容器详解

std::map 是 C++ 标准模板库(STL)中的一种关联容器,用于存储键值对(key-value pairs)并根据键自动排序。它通常基于红黑树实现,提供了高效的插入、删除和查找操作。本文将详细介绍 std::map 的使用,包括注意事项、引用头文件、函数构造、对象初始化、元素访问、迭代器、容器操作、修改器和元素比较等方面,并通过代码示例进行说明。

注意事项

  1. 键的唯一性std::map 中的键是唯一的,如果插入具有相同键的多个元素,后插入的元素会覆盖先前的元素。
  2. 自动排序std::map 会根据键的默认比较方式(通常是 < 运算符)自动排序元素。
  3. 复杂度:插入、删除和查找操作的时间复杂度通常为 O(log n),其中 n 是容器中元素的数量。
  4. 内存分配std::map 可能会动态分配内存来存储元素,因此在使用时需要注意内存管理。

引用头文件

要使用 std::map,首先需要包含 <map> 头文件:

cpp 复制代码
#include <map>

函数构造与对象初始化

std::map 提供了多种构造函数来初始化容器。

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

int main() {
    // 默认构造函数
    std::map<int, std::string> map1;

    // 使用列表初始化
    std::map<int, std::string> map2 = {
        {1, "one"},
        {2, "two"},
        {3, "three"}
    };

    // 使用范围初始化(假设有另一个 map 或 pair 数组)
    // std::map<int, std::string> map3(map2.begin(), map2.end());

    return 0;
}

元素访问

可以通过键直接访问元素,也可以使用 find 函数来查找元素。

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

int main() {
    std::map<int, std::string> map = {
        {1, "one"},
        {2, "two"},
        {3, "three"}
    };

    // 通过键直接访问
    std::cout << "Key 1: " << map[1] << std::endl;

    // 使用 find 函数
    auto it = map.find(2);
    if (it != map.end()) {
        std::cout << "Key 2: " << it->second << std::endl;
    } else {
        std::cout << "Key 2 not found." << std::endl;
    }

    // 尝试访问不存在的键(会插入新元素)
    std::cout << "Key 4 (new): " << map[4] << std::endl; // 输出默认值,并插入 {4, ""}

    return 0;
}

迭代器

std::map 提供了迭代器来遍历容器中的元素。

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

int main() {
    std::map<int, std::string> map = {
        {1, "one"},
        {2, "two"},
        {3, "three"}
    };

    // 使用迭代器遍历
    for (auto it = map.begin(); it != map.end(); ++it) {
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }

    // 使用范围 for 循环遍历
    for (const auto& pair : map) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

容器操作

std::map 提供了一些成员函数来管理容器,例如 sizeemptyclear 等。

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

int main() {
    std::map<int, std::string> map = {
        {1, "one"},
        {2, "two"},
        {3, "three"}
    };

    // 获取容器大小
    std::cout << "Size: " << map.size() << std::endl;

    // 检查容器是否为空
    std::cout << "Is empty: " << std::boolalpha << map.empty() << std::endl;

    // 清空容器
    map.clear();
    std::cout << "After clear, is empty: " << std::boolalpha << map.empty() << std::endl;

    return 0;
}

修改器

std::map 提供了多种修改元素的方法,例如 inserteraseoperator[] 等。

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

int main() {
    std::map<int, std::string> map = {
        {1, "one"},
        {2, "two"},
        {3, "three"}
    };

    // 插入新元素
    auto result = map.insert({4, "four"});
    if (result.second) {
        std::cout << "Inserted Key 4: " << result.first->first << ", Value: " << result.first->second << std::endl;
    } else {
        std::cout << "Insertion failed, key 4 already exists." << std::endl;
    }

    // 使用 operator[] 修改元素(如果键不存在,则插入新元素)
    map[2] = "TWO";
    std::cout << "Modified Key 2: " << map[2] << std::endl;

    // 删除元素
    map.erase(3);
    std::cout << "After erase key 3, is key 3 in map? " << std::boolalpha << (map.find(3) != map.end()) << std::endl;

    return 0;
}

元素比较

std::map 中的元素按键自动排序,默认使用 < 运算符进行比较。如果需要自定义比较方式,可以传递自定义的比较函数对象或仿函数。

cpp 复制代码
#include <iostream>
#include <map>
#include <string>
#include <functional> // for std::greater

struct CustomCompare {
    bool operator()(int lhs, int rhs) const {
        return lhs > rhs; // 降序比较
    }
};

int main() {
    // 默认按升序排序
    std::map<int, std::string> map1 = {
        {3, "three"},
        {1, "one"},
        {2, "two"}
    };

    for (const auto& pair : map1) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    // 使用自定义比较器按降序排序
    std::map<int, std::string, CustomCompare> map2 = {
        {3, "three"},
        {1, "one"},
        {2, "two"}
    };

    for (const auto& pair : map2) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    // 使用 std::greater 作为比较器
    std::map<int, std::string, std::greater<int>> map3 = {
        {3, "three"},
        {1, "one"},
        {2, "two"}
    };

    for (const auto& pair : map3) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

总结

std::map 是一种功能强大的关联容器,适用于需要按键快速查找、插入和删除元素的场景。通过掌握其构造函数、元素访问、迭代器、容器操作、修改器和元素比较等常用方法,可以高效地利用 std::map 进行编程。本文详细介绍了 std::map 的使用方法和注意事项,并通过代码示例进行了说明,希望能帮助读者更好地理解和使用 std::map


相关推荐
你好,奋斗者!27 分钟前
#define STEUER_A_H {PWM_A_ON}
c语言
吴_知遇1 小时前
【华为OD机试真题】428、连续字母长度 | 机试真题+思路参考+代码解析(E卷)(C++)
开发语言·c++·华为od
LaoWaiHang1 小时前
MFC案例:使用键盘按键放大、缩小窗口图像的实验
c++·mfc
basketball6161 小时前
Python torchvision.transforms 下常用图像处理方法
开发语言·图像处理·python
到底怎么取名字不会重复1 小时前
Day10——LeetCode15&560
c++·算法·leetcode·哈希算法·散列表
宁酱醇1 小时前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug
啊吧怪不啊吧2 小时前
Linux常见指令介绍下(入门级)
linux·开发语言·centos
谷晓光2 小时前
Python 中 `r` 前缀:字符串处理的“防转义利器”
开发语言·python
Tiger Z2 小时前
R 语言科研绘图第 41 期 --- 桑基图-基础
开发语言·r语言·贴图
chuxinweihui2 小时前
数据结构——二叉树,堆
c语言·开发语言·数据结构·学习·算法·链表