跳到内容

关联容器:set与map ​

序列容器按下标存取,关联容器则按键存取。STL 的关联容器底层通常是红黑树(有序)或哈希表(无序,名字带 unordered_ 前缀)。本节聚焦最常用的两类:std::set(只存键)和 std::map(存键值对)。它们共同的特点是自动保持键有序、查找效率高(有序版本为 O(log n))。

set:有序唯一集合 ​

std::set 里的元素自动排序且不重复。插入时它帮你去重并维持顺序,无需手动调用 sort:

cpp
#include <iostream>
#include <set>
#include <string>

int main()
{
    std::set<std::string> tags{"读书", "跑步", "读书", "编程", "跑步"};
    // 重复的"读书""跑步"只保留一份,且自动排序

    for (const auto& t : tags)
        std::cout << t << "\n";

    auto result = tags.insert("冥想");
    std::cout << "插入冥想是否成功:" << result.second << "\n";
    auto result2 = tags.insert("读书");
    std::cout << "再次插入读书是否成功:" << result2.second << "\n";

    auto it = tags.find("编程");
    if (it != tags.end())
        std::cout << "找到:" << *it << "\n";
    return 0;
}

insert 返回一个 pair:第一个是迭代器指向该元素,第二个是 bool 表示是否真的新插入(已存在则为 false)。find 找不到返回 end(),判断结果必须和 end() 比较。

multiset:允许重复 ​

把 set 换成 multiset 就允许同一键出现多次:

cpp
#include <iostream>
#include <set>
#include <string>

int main()
{
    std::multiset<std::string> votes{"好", "好", "中", "好", "差", "中"};
    std::cout << "好 票数 = " << votes.count("好") << "\n";
    std::cout << "中 票数 = " << votes.count("中") << "\n";

    // 同一键的元素相邻排列
    for (const auto& v : votes)
        std::cout << v << " ";
    std::cout << "\n";
    return 0;
}

count 对 set 只能返回 0 或 1,对 multiset 才能返回真实数量。

set 的集合运算 ​

STL 通用算法提供了 std::set_union、std::set_intersection、std::set_difference,要求输入已排序(set 天然满足):

cpp
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>

int main()
{
    std::set<int> A{1, 3, 5, 7, 9};
    std::set<int> B{2, 3, 5, 8};

    std::cout << "并集:";
    std::set_union(A.begin(), A.end(), B.begin(), B.end(),
                   std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    std::cout << "交集:";
    std::set_intersection(A.begin(), A.end(), B.begin(), B.end(),
                          std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    std::cout << "差集 A-B:";
    std::set_difference(A.begin(), A.end(), B.begin(), B.end(),
                        std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
    return 0;
}

std::ostream_iterator<T>(std::cout, " ") 是一个输出流迭代器,把每个元素写到 cout 并跟一个分隔符,常用于调试时快速打印容器。结果存入另一个 set 时,用 std::inserter(target, target.begin()) 作为目标迭代器。

map:键值对字典 ​

std::map 按"键"排序存储"键值对"。每对是一个 std::pair<const Key, Value>。访问用 [] 或 at,前者键不存在时会插入默认值,后者抛异常:

cpp
#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<std::string, int> stock;
    stock["笔"] = 30;
    stock["本"] = 12;
    stock["墨"] = 5;
    stock["笔"] += 10;          // 已存在则修改

    std::cout << "笔库存 = " << stock["笔"] << "\n";

    // 不存在的键:[] 会偷偷插入一个 0
    std::cout << "橡皮 = " << stock["橡皮"] << "\n";   // 此处插入了 "橡皮"=>0
    std::cout << "当前键数 = " << stock.size() << "\n";

    // at() 不存在会抛 std::out_of_range,不会偷偷插入
    try {
        std::cout << stock.at("尺子") << "\n";
    } catch (const std::out_of_range&) {
        std::cout << "尺子不存在\n";
    }

    // 遍历:first 是键,second 是值
    for (const auto& kv : stock)
        std::cout << kv.first << " => " << kv.second << "\n";
    return 0;
}

[] 的"自动插入"特性很方便但也是隐患:用 [] 查一个不存在的键会悄悄改变容器。只想查询、不想插入时,用 find 或 at。

multimap:一键多值 ​

std::multimap 允许同一键对应多个值,且不支持 [](因为一键多值,[] 语义不明确)。插入用 insert,查询用 equal_range:

cpp
#include <iostream>
#include <map>
#include <string>

int main()
{
    std::multimap<int, std::string> areaCode;
    areaCode.insert({10, "北京"});
    areaCode.insert({21, "上海"});
    areaCode.insert({10, "燕郊"});
    areaCode.insert({21, "浦东"});

    std::cout << "区号 10 的条目数 = " << areaCode.count(10) << "\n";

    // equal_range 返回一个 pair,表示该键对应的范围
    auto range = areaCode.equal_range(21);
    for (auto it = range.first; it != range.second; ++it)
        std::cout << it->first << ": " << it->second << "\n";
    return 0;
}

equal_range 返回两个迭代器组成的区间 [first, second),覆盖某键的全部元素。这是在 multimap / multiset 上做范围查询的标准手段。

lower_bound 与 upper_bound ​

更细粒度的范围查询用 lower_bound(第一个不小于键的位置)和 upper_bound(第一个大于键的位置):

cpp
#include <iostream>
#include <set>

int main()
{
    std::set<int> s{2, 4, 6, 8, 10, 12};
    // 想找 [5, 10] 范围内的元素
    auto lo = s.lower_bound(5);   // 指向 6
    auto hi = s.upper_bound(10);  // 指向 12
    for (auto it = lo; it != hi; ++it)
        std::cout << *it << " ";  // 6 8 10
    std::cout << "\n";
    return 0;
}

这对函数在 set、map、multiset、multimap 上都有成员版本(比同名通用算法更快,因为利用了树的有序结构)。

课后练习 ​

  1. 去重排序:给定一个含重复元素的 std::vector<int>,用一个 std::set<int> 接收它(构造时传迭代器范围),遍历 set 打印结果,体会"自动去重 + 自动排序"。
  2. 词频统计:读入一组单词存入 std::vector<std::string>,用 std::map<std::string, int> 统计每个单词出现次数。提示:map[word]++ 在键不存在时会先插入 0 再自增。最后按字典序遍历打印。
  3. multimap 查询:用 std::multimap<int, std::string> 存"年龄 → 姓名"的多对多关系(同一年龄可有多个姓名)。用 count 查某年龄人数,用 equal_range 遍历打印某年龄的全部姓名。
  4. 集合运算收集:用 std::set_union 求两个 std::set<int> 的并集,但结果不直接打到 cout,而是通过 std::inserter 存入第三个 set,再遍历验证。