✅ 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
的区别
set | unordered_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) |