「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


相关推荐
上理考研周导师3 分钟前
【虚拟仪器技术】Labview虚拟仪器技术应用教程习题参考答案[13页]
服务器·开发语言
ty_sj8 分钟前
【FreeRtos】任务调度器可以被挂起吗?
c语言·嵌入式硬件
郭涤生14 分钟前
Chapter 5: The Standard Library (C++20)_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
叶孤程31 分钟前
Qt图形化界面为何总被“冷落“?
开发语言·c++·qt
葵野寺37 分钟前
【多线程】线程池
java·开发语言·java-ee·web app
写代码写到手抽筋1 小时前
C++多线程的性能优化
java·c++·性能优化
二进制人工智能1 小时前
【QT5 网络编程示例】UDP 通信
c++·qt
高林雨露1 小时前
Java 与 Kotlin 对比学习指南(二)
java·开发语言·kotlin
Maple_land1 小时前
# C++初阶——内存管理
c++
笑口常开xpr1 小时前
C 语 言 --- 整 形 提 升
c语言·开发语言