您的位置:首页 > 文旅 > 旅游 > C++ STL之set和unordered_set

C++ STL之set和unordered_set

2025/5/4 5:52:24 来源:https://blog.csdn.net/qq_44961737/article/details/142153995  浏览:    关键词:C++ STL之set和unordered_set

一.概述

set是一个关联容器,它存储了一组唯一的元素,并按照一定的顺序进行排序,并提供了高效的元素查找、插入和删除操作。而unordered_set与set的区别在于unordered_set是无序的

注:

  1. 在内部,元素不按任何特定顺序排序,元素放入哪个存储完全取决于其值的哈希值。这允许快速访问各个元素,因为一旦计算出哈希值,它就会引用该元素被放入的内存中。
  2. 不再以键值对的形式存储数据,而是直接存储数据的值
  3. 容器内部存储的各个元素的值都互不相等,且不能被修改,因为修改可能会更改元素的哈希值并损坏容器。

二. 初始化

2.1 头文件

#include <unordered_set>
#include <set>

2.2 函数声明

std::unordered_set<Key, Hash = std::hash<Key>, Pred = std::equal_to<Key>, Alloc = std::allocator<Key>>
// Key 是存储的元素类型。
// Hash 是一个函数或函数对象,用于生成元素的哈希值,默认为 std::hash<Key>。
// Pred 是一个二元谓词,用于比较两个元素是否相等,默认为 std::equal_to<Key>。
// Alloc 是分配器类型,用于管理内存分配,默认为 std::allocator<Key>。set<元素类型> 容器名;

2.3 初始化

unordered_set<int> mySet; //默认构造
unordered_set<int> mySet2(mySet1); //拷贝构造
unordered_set<int> mySet3(move(mySet2)); //移动构造
unordered_set<int> mySet4(set1.begin(), set1.end()); //迭代器构造
unordered_set<int> mySet5(num,num+10);    //数组构造
unordered_set<int> mySet6 {1,2,3,4};//赋值初始化

3.成员函数

成员函数功能
begin返回指向容器中第一个元素的正向迭代器。
cbegin和 begin() 功能相同,只不过其返回的是 const 类型的正向迭代器。
end返回指向容器中最后一个元素之后位置的正向迭代器。
cend和 end() 功能相同,只不过其返回的是 const 类型的正向迭代器。
empty若容器为空,则返回 true;否则 false。
size容器中元素个数。
max_size返回容器所能容纳元素的最大个数,依操作系统而定。
clear清空容器
insert插入元素或节点
insert_range插入一系列元素
emplace向容器中添加新元素,效率比 insert() 方法高。
emplace_hint向容器中添加新元素,效率比 insert() 方法高。
erase删除指定元素。
swap交换 2 个 unordered_set 容器存储的元素。
count在容器中查找值为 key 的元素的个数。
find查找以值为 key 的元素,若找到,则返回一个指向该元素的正向迭代器;反之,则返回一个指向容器中最后一个元素之后位置的迭代器。

四. 遍历

#include<iostream>
#include<unordered_set>using namespace std;int main(){unordered_set<string> mySet1 = {"one", "two", "three","four"};unordered_set<string> mySet2 = {"five", "six", "seven"};string str = "zero";// 使用迭代器遍历for(unordered_set<string>::iterator it = mySet1.begin(); it!=mySet1.end(); it++){cout<< *it << " ";}// 确定类型mySet1.insert(str); // 插入单个元素for(const string& x: mySet1){cout<< x << " ";}// 类型推导mySet1.insert(mySet2.begin(),mySet2.end()); // 使用范围迭代器插入for(const auto& x: mySet1){cout<< x << " ";}return 0;
}/*
output:
four three two one 
one two zero three four
seven one two six zero three five four
*/

参考:
https://en.cppreference.com/w/cpp/container/unordered_set
https://www.runoob.com/cplusplus/cpp-libs-unordered_set.html
https://m.biancheng.net/view/7250.html

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com