这一章整理关联容器:setpairmap。它们的核心是“按键组织数据”,适合做去重、索引、配置表、统计表和对象映射。

5.3 set 存储规则

set 保存唯一元素,并按比较规则排序。

1
std::set<int> ids = {3, 1, 2, 2};

最终只有 1,2,3

5.4 set 大小替换

set 不能像数组一样通过下标修改元素,因为修改可能破坏排序规则。通常要先删除再插入。

1
2
ids.erase(2);
ids.insert(20);

5.5 set 重复元素

set 会自动去重;如果需要允许重复,用 multiset

容器 是否允许重复
set 不允许
multiset 允许

5.6 set 查找计数

1
2
3
4
5
if (ids.find(3) != ids.end()) {
std::cout << "exists\n";
}

std::cout << ids.count(3) << std::endl;

setcount 通常只会返回 0 或 1。

5.7 pair

pair 用来保存两个相关值,常见于 map 的键值对。

1
2
std::pair<int, std::string> item = {1, "admin"};
std::cout << item.first << " " << item.second << std::endl;

5.8 map 对象构造

map 保存键值对,键唯一并自动排序。

1
2
std::map<std::string, int> scores;
scores["math"] = 90;

5.9 map 对象数据

操作 说明
operator[] 不存在时会插入默认值
at() 不存在时抛异常
find() 查询是否存在
insert() 插入键值对

复盘重点:如果只是查询,不要随便用 [],它可能改变容器。

6.0 map 增删改查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <map>
#include <string>

int main() {
std::map<std::string, int> scores;

scores.insert({"math", 90});
scores["english"] = 85;

auto it = scores.find("math");
if (it != scores.end()) {
it->second = 95;
}

scores.erase("english");

for (const auto &item : scores) {
std::cout << item.first << ": " << item.second << std::endl;
}

return 0;
}

安全开发复盘

场景 推荐容器
去重 ID set
名称到对象映射 map
配置项 map<string, string>
统计次数 map<string, int>
保留插入顺序 考虑 vector 或其他结构

常见坑

问题 说明
[] 查询 不存在时会插入默认值
自定义键未定义比较 map 不知道如何排序
迭代时删除 要使用正确删除写法
键可变 键变化会破坏排序结构

学习检查清单

检查项 状态
能说明 set 为什么自动去重 待复盘
能使用 findcount 查询元素 待复盘
能说明 pairmap 键值对关系 待复盘
能区分 map[]at()find() 待复盘
能用 map 写一个简单统计表 待复盘