C++容器对比:map与unordered_map全解析

C++关联式容器详解:map、set与unordered_map

一、核心原理
  1. map与set(有序容器)

    • 数据结构 :基于红黑树(自平衡二叉搜索树)
    • 特性 :
      • 元素按严格弱排序 (默认<)自动排序
      • 插入/删除/查找时间复杂度:O(\\log n)
    • map :存储键值对 (key, value)
    • set :仅存储唯一键 key
  2. unordered_map(无序容器)

    • 数据结构 :基于哈希表(散列表)
    • 特性 :
      • 元素顺序不可控(依赖哈希函数)
      • 平均插入/删除/查找时间复杂度:O(1)
      • 最坏情况:O(n)(哈希冲突严重时)
二、关键操作对比
操作 map/set unordered_map
插入 insert() insert()
查找 find() find()
删除 erase() erase()
遍历 有序迭代 无序迭代
自定义排序 支持比较器 不支持
自定义哈希 不支持 需定义哈希函数
三、典型应用场景
  1. map示例:词频统计
cpp 复制代码
#include <map>
#include <string>

std::map<std::string, int> wordCount;
for (const auto& word : words) {
    wordCount[word]++; // 自动初始化值为0
}
  1. set示例:去重排序
cpp 复制代码
#include <set>
#include <vector>

std::vector<int> nums = {3, 1, 4, 1, 5};
std::set<int> uniqueSet(nums.begin(), nums.end()); // 输出:{1, 3, 4, 5}
  1. unordered_map示例:缓存系统
cpp 复制代码
#include <unordered_map>

std::unordered_map<std::string, Data> cache;
if (cache.find(key) == cache.end()) {
    cache[key] = fetchData(); // 快速查找
}
四、性能优化要点
  1. map/set:

    • 自定义比较器提升效率
    cpp 复制代码
    struct CaseInsensitiveCompare {
        bool operator()(const std::string& a, const std::string& b) const {
            return std::tolower(a[0]) < std::tolower(b[0]);
        }
    };
    std::map<std::string, int, CaseInsensitiveCompare> customMap;
  2. unordered_map:

    • 预分配桶数量减少冲突
    cpp 复制代码
    std::unordered_map<int, std::string> preallocMap;
    preallocMap.reserve(1000); // 预分配空间
    • 自定义哈希函数
    cpp 复制代码
    struct CustomHash {
        size_t operator()(const MyClass& obj) const {
            return std::hash<int>()(obj.id) ^ std::hash<std::string>()(obj.name);
        }
    };
五、选择策略
  1. 需有序遍历 或范围查询 :选map/set
  2. 追求极致查找速度 且不要求顺序 :选unordered_map
  3. 内存敏感场景:红黑树(map/set)通常比哈希表更省内存

注意 :unordered_map的迭代器失效规则与map不同,插入操作可能导致全部迭代器失效(桶重建时)。

相关推荐
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
weilx12344 天前
C++笔记-文件IO-<fcntl.h>
c++
Smileyqp沛沛4 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·4 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁4 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven4 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
程序猿编码4 天前
告别改源码适配模型:纯 C++ 可配置 LLM 推理引擎,全格式全结构兼容
c++·大模型·llm·推理引擎
此生决int4 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++