当前位置: 首页 > article >正文

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 在需要快速查找和唯一性保证的数据处理上非常强大。


http://www.kler.cn/news/335433.html

相关文章:

  • Oracle架构之物理存储中各种文件详解
  • 自动驾驶汽车横向控制方法研究综述
  • 【EXCEL数据处理】000014 案例 EXCEL分类汇总、定位和创建组。附多个操作案例。
  • 数据结构_绪论(选择题)
  • 前端的全栈混合之路Meteor篇(二):RPC方法注册及调用
  • IntelliJ IDEA 2024.2 新特性概览
  • HTML ASCII:Web 开发中的字符编码基础
  • 计算机毕业设计 家校互联管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • vue3使用three.js加载.obj模型示例
  • 项目管理-信息技术发展
  • java:缓存 json格式
  • 阿里云域名注册购买和备案
  • 工厂模式与建造者模式的区别
  • 二、Python(项目创建、常见的设置、print函数)
  • SQL Inject-基于报错的信息获取
  • JavaScript中的高阶函数
  • C语言—单链表
  • 什么是reactor以及其三种版本
  • STM32定时器(TIM)
  • jQuery 选择器