C++ std::unordered_set 容器

std::unordered_set 是 C++ 标准库中的一个无序集合容器,它使用哈希表实现来存储唯一的元素。std::unordered_set 提供了一系列的成员函数和操作符来操作集合中的元素。

使用 std::unordered_set

要使用 std::unordered_set,需要包含 <unordered_set> 头文件,并使用 std::unordered_set 模板类定义集合对象。

常用接口

  1. 构造函数:

    • unordered_set(): 创建一个空的集合。
    • unordered_set(size_type bucketCount): 创建一个空的集合,并指定桶的数量。
    • unordered_set(size_type bucketCount, const Hash& hashFunction, const KeyEqual& keyEqual): 创建一个空的集合,并指定桶的数量、哈希函数和键相等函数。
    • unordered_set(InputIt first, InputIt last): 创建一个集合,并用迭代器范围 [first, last) 区间内的元素进行初始化。
    • unordered_set(const unordered_set& other): 创建一个集合,并用另一个集合进行初始化。
    • unordered_set(unordered_set&& other): 创建一个集合,并用另一个集合进行移动构造。
  2. 成员函数:

    • begin(): 返回指向集合中第一个元素的迭代器。
    • end(): 返回指向集合中最后一个元素之后位置的迭代器。
    • empty(): 检查集合是否为空。
    • size(): 返回集合中元素的个数。
    • max_size(): 返回集合能够容纳的最大元素个数。
    • clear(): 清空集合的元素。
    • insert(const value_type& value): 插入一个元素到集合中。
    • insert(value_type&& value): 插入一个元素到集合中(使用移动语义)。
    • emplace(Args&&... args): 在集合中使用构造函数参数 args 插入一个元素。
    • erase(const Key& key): 从集合中删除给定的键对应的元素。
    • find(const Key& key): 查找给定的键,返回指向该键的元素的迭代器。
    • count(const Key& key): 返回集合中给定键的数量。
    • bucket_count(): 返回集合中桶的数量。
    • load_factor(): 返回集合中元素的平均装载因子。
    • rehash(size_type count): 重新分配桶的数量,使其足够容纳 count 个桶。
    • reserve(size_type count): 提前为至少 count 个元素分配足够的桶空间。
  3. 迭代器:

    • iterator: 用于遍历集合中元素的正向迭代器。
    • const_iterator: 用于遍历集合中元素的常量正向迭代器。
    • reverse_iterator: 用于逆向遍历集合中元素的迭代器。
    • const_reverse_iterator: 用于逆向遍历集合中元素的常量迭代器。
  4. 运算符:

    • operator=(): 赋值运算符,用另一个集合替换当前集合的内容。
    • operator==(), operator!=(), operator<(), operator>(), operator<=(), operator>=(): 用于比较两个集合的相等性、大小关系等。

示例代码

#include <iostream>
#include <unordered_set>

int main() {
    std::unordered_set<int> mySet;

    // 插入元素
    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);

    // 遍历集合并打印元素
    std::cout << 'Set elements: '; 
    for (const auto& element : mySet) {
        std::cout << element << ' '; 
    }
    std::cout << std::endl;

    // 查找元素
    int key = 20;
    auto it = mySet.find(key);
    if (it != mySet.end()) {
        std::cout << key << ' found in the set' << std::endl;
    } else {
        std::cout << key << ' not found in the set' << std::endl;
    }

    // 删除元素
    mySet.erase(20);

    // 检查集合是否为空
    if (mySet.empty()) {
        std::cout << 'Set is empty' << std::endl;
    } else {
        std::cout << 'Set is not empty' << std::endl;
    }

    return 0;
}

在上述示例中,我们首先创建了一个 std::unordered_set<int> 对象 mySet。然后,使用 insert() 函数插入了一些元素。使用范围-based for 循环遍历集合并打印元素。使用 find() 函数查找元素,并根据返回值判断是否找到了指定元素。使用 erase() 函数删除元素。最后,使用 empty() 函数检查集合是否为空。

总结

std::unordered_set 是 C++ 中一个强大的无序集合容器,它提供了高效的元素存储和操作方式。通过理解其接口和功能,您可以利用 std::unordered_set 轻松实现各种数据处理任务。

C++ unordered_set 容器详解:接口、用法和示例

原文地址: https://www.cveoy.top/t/topic/QG8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录