STL-unordered_set容器总结
unordered_set
是 C++ STL 中的一种容器,用于存储唯一元素,底层实现通常使用哈希表。基本用法如下:以下是 unordered_set
的完整用法整理,包括基本操作和示例代码:
1. 包含头文件
#include <unordered_set>
2. 声明与初始化
std::unordered_set<int> mySet = {1, 2, 3};
3. 插入元素
mySet.insert(4); // 插入单个元素
mySet.emplace(5); // 直接构造元素
4. 查找元素
if (mySet.find(2) != mySet.end()) {
// 找到元素
}
5. 检查元素是否存在
if (mySet.count(3) > 0) {
// 元素存在
}
6. 删除元素
mySet.erase(1); // 删除指定元素
7. 获取大小与清空
size_t size = mySet.size(); // 获取元素个数
mySet.clear(); // 清空集合
8. 检查是否为空
if (mySet.empty()) {
// 集合为空
}
9. 遍历元素
for (const auto& elem : mySet) {
std::cout << elem << " ";
}
10. 自定义哈希函数与相等比较函数
struct CustomType {
int x;
int y;
};
struct HashFunction {
size_t operator()(const CustomType& ct) const {
return std::hash<int>()(ct.x) ^ std::hash<int>()(ct.y);
}
};
struct EqualFunction {
bool operator()(const CustomType& ct1, const CustomType& ct2) const {
return ct1.x == ct2.x && ct1.y == ct2.y;
}
};
std::unordered_set<CustomType, HashFunction, EqualFunction> customSet;
11. 桶迭代器
for (size_t i = 0; i < mySet.bucket_count(); ++i) {
for (auto it = mySet.begin(i); it != mySet.end(i); ++it) {
std::cout << *it << " ";
}
}
12. 合并集合
std::unordered_set<int> otherSet = {4, 5, 6};
mySet.insert(otherSet.begin(), otherSet.end());
13. 交换两个集合
std::unordered_set<int> anotherSet;
mySet.swap(anotherSet); // 交换内容
14. 访问底层桶数量
size_t bucketCount = mySet.bucket_count(); // 获取桶数量
这些操作使 unordered_set
在需要快速查找和唯一性保证的数据处理上非常强大。