Z
ZHANK
编程在线教程C++ 教程std::map 与 std::set
模板与 STL

std::map 与 std::set

map 键值对、set 集合、unordered_map/set 哈希版本、自定义比较

std::map 与 std::set

关联容器按 key 组织数据:map 存键值对,set 存唯一值。需要快速查找时用它们。

学完本章你将: 掌握 map/set、unordered_map/set、自定义比较。


std::map —— 有序键值对

cpp
#include <iostream>
#include <map>

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

    ages["小明"] = 25;             // 插入或修改
    ages["小红"] = 22;
    ages.insert({"小刚", 30});     // 另一种插入方式

    // 查找
    auto it = ages.find("小明");
    if (it != ages.end()) {
        std::cout << it->first << ":" << it->second << " 岁\n";
    }

    // 遍历(按 key 排序)
    for (const auto &[name, age] : ages) {  // C++17 结构化绑定
        std::cout << name << " → " << age << "\n";
    }

    return 0;
}

std::set —— 唯一集合

cpp
#include <set>

std::set<int> s = {3, 1, 4, 1, 5, 9};
// s = {1, 3, 4, 5, 9}——自动排序 + 去重

s.insert(2);   // {1, 2, 3, 4, 5, 9}
s.erase(4);    // {1, 2, 3, 5, 9}

if (s.contains(3)) { /* C++20 */ }

unordered_map / unordered_set —— 哈希版本

cpp
#include <unordered_map>

// 平均 O(1) 查找,不排序
std::unordered_map<std::string, int> ages;
ages["小明"] = 25;

// map vs unordered_map
// map:      红黑树,O(log n),有序,稳定迭代
// unordered_map: 哈希表,O(1) 平均,无序,查找更快

自定义比较

cpp
// map 用 greater 降序
std::map<int, std::string, std::greater<int>> m;
m[1] = "one"; m[2] = "two";  // {2: "two", 1: "one"}

// 自定义比较函数
struct ByLength {
    bool operator()(const std::string &a, const std::string &b) const {
        return a.length() < b.length();
    }
};
std::set<std::string, ByLength> words;