std::unordered_set 哈希集合介绍

std::unordered_set 是什么

  • 它是 C++ 标准库 里的 哈希集合(无序集合)。

  • 来自头文件 <unordered_set>

  • 底层是 哈希表,所以:

    • 插入、查找、删除都是 平均 O(1)

    • 元素 无序,按哈希值存放。

    • 不允许重复元素。


✅ 常用功能

功能解释
insert插入元素
find查找元素
erase删除元素
count判断是否存在(0 或 1)
size当前元素个数
clear清空集合
遍历用范围 for 或迭代器

📌 头文件

#include <unordered_set>

📌 基本示例

#include <iostream>
#include <unordered_set>
using namespace std;

int main() {
    unordered_set<int> s;

    // 插入元素
    s.insert(5);
    s.insert(2);
    s.insert(7);

    // 查找元素
    if (s.find(5) != s.end()) {
        cout << "5 is in the set" << endl;
    }

    // 判断是否存在
    if (s.count(2)) {
        cout << "2 is in the set" << endl;
    }

    // 删除元素
    s.erase(5);

    // 遍历
    for (int x : s) {
        cout << x << " ";
    }
    cout << endl;

    // 元素个数
    cout << "size = " << s.size() << endl;

    // 清空
    s.clear();
    cout << "size after clear = " << s.size() << endl;

    return 0;
}

✅ 常见场景

unordered_set 很适合:

  • 判断某个元素是否出现过

  • 去重(去除重复)

  • 用作哈希表实现集合操作

  • 需要高效查找但不关心顺序


⚡ 和 set 的区别

setunordered_set
底层红黑树哈希表
元素顺序自动有序无序
查找、插入O(logN)O(1)(平均)
是否可重复都不允许重复都不允许重复

✅ 进阶:自定义类型

unordered_set 如果要存放自定义类型(如结构体),要自己提供 ==hash

示例:

#include <iostream>
#include <unordered_set>
using namespace std;

struct Point {
    int x, y;
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

// 自定义 hash 函数
struct HashPoint {
    size_t operator()(const Point& p) const {
        return hash<int>()(p.x) ^ (hash<int>()(p.y) << 1);
    }
};

int main() {
    unordered_set<Point, HashPoint> points;
    points.insert({1, 2});
    points.insert({3, 4});

    if (points.count({1, 2})) {
        cout << "Point (1, 2) exists!" << endl;
    }

    return 0;
}

⚡ 总结

操作用法示例
插入s.insert(x);
查找s.find(x) != s.end()
判断存在s.count(x)
删除s.erase(x)
遍历for (auto x : s)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值