【C++关联式容器】unordered_set

目录

unordered_set

1. 关联式容器额外的类型别名

2. 哈希桶

3. 无序容器对关键字类型的要求

4. Member functions

4.1 constructor、destructor、operator=

4.1.1 constructor

4.1.2 destructor

4.1.3 operator= 

4.2 Capacity

​4.2.1 empty

4.2.2 size

4.2.3 max_size

4.3 Iterators

4.4 Element lookup

4.4.1 find

4.4.2 count

4.4.3 equal_range

4.5 Modifiers

4.5.1 emplace

4.5.2 emplace_hint

4.5.3 insert

4.5.4 erase

4.5.5 clear

4.5.6 swap

4.6 Buckets

4.6.1 bucket_count

4.6.2 max_bucket_count

4.6.3 bucket_size

4.6.4 bucket

4.7 Hash policy

4.7.1 load_factor

4.7.2 max_load_factor

4.7.3 rehash

4.7.4 reserve

4.8 Observers

4.8.1 hash_function

4.8.2 key_eq

4.8.3 get_allocator

5. Non-member function overloads

5.1 operators

5.2 swap

6. unordered_set对象的遍历方法

6.1 迭代器

6.2 范围for


unordered_set

template < class Key,                        // unordered_set::key_type/value_type
           class Hash = hash<Key>,           // unordered_set::hasher
           class Pred = equal_to<Key>,       // unordered_set::key_equal
           class Alloc = allocator<Key>      // unordered_set::allocator_type
           > class unordered_set;

unordered_set是一种容器,它存储的元素没有特定的顺序,允许根据元素的值快速获取单个元素。

在unordered_set中,一个元素的值与它的键同时存在,从而唯一地标识它。键是不可变的,因此unordered_set中的元素一旦进入容器就不能被修改——但它们可以被插入和删除。

在内部,unordered_set中的元素没有按任何特定的顺序排序,而是根据它们的哈希值组织成,以允许直接通过值快速访问各个元素(平均时间复杂度是常数)。

在通过键访问单个元素时,unordered_set容器比set容器更快,尽管在通过元素子集进行范围迭代时通常效率较低。

容器中的迭代器至少是前向迭代器。

unordered_set定义在头文件unordered_set和命名空间std中。

1. 关联式容器额外的类型别名

key_type此容器类型的关键字类型
mapped_type每个关键字关联的类型;只适用于map
value_type对于set,与key_type相同
对于map,为pair<const key_type, mapped_type>

对于set类型,key_type和value_type是一样的:set中保存的值就是关键字。在一个map中,元素是键值对。即,每个元素是一个pair对象,包含一个关键字和一个关联的值。由于我们不能改变一个元素的关键字,因此这些pair的关键字部分是const的:

set<string>::value_type vl;       // v1是一个string
set<string>::key_type v2;         // v2是一个string
map<string, int>::value_type v3;  // v3是一个pair<const string, int>
map<string, int>::key_type v4;    // v4是一个string
map<string, int>::mapped_type v5; // v5是一个int

与序列式容器一样,我们使用作用域运算符来提取一个类型的成员——例如,map<string, int>::key_type。

只有map类型(unordered_map、unordered_multimap、multimap和map)才定义了mapped_type。

2. 哈希桶

无序容器在存储上组织为一组桶,每个桶保存零个或多个元素。无序容器使用一个哈希函数将元素映射到桶。为了访问一个元素,容器首先计算元素的哈希值,它指出应该搜索哪个桶。容器将具有一个特定哈希值的所有元素都保存在相同的桶中。如果容器允许重复关键字,所有具有相同关键字的元素也都会在同一个桶中。因此,无序容器的性能依赖于哈希函数的质量和桶的数量和大小。

对于相同的参数,哈希函数必须总是产生相同的结果。理想情况下,哈希函数还能将每个特定的值映射到唯一的桶。但是,将不同关键字的元素映射到相同的桶也是允许的。当一个桶保存多个元素时,需要顺序搜索这些元素来查找我们想要的那个。计算一个元素的哈希值和在桶中搜索通常都是很快的操作。但是,如果一个桶中保存了很多元素,那么查找一个特定元素就需要大量比较操作。

3. 无序容器对关键字类型的要求

默认情况下,无序容器使用关键字类型的==运算符来比较元素,它们还使用一个hash<key_type>类型的对象来生成每个元素的哈希值。标准库为内置类型(包括指针)提供了hash模板。还为一些标准库类型,包括string和智能指针类型定义了hash。因此,我们可以直接定义关键字是内置类型(包括指针类型)、string还有智能指针类型的无序容器。

但是,我们不能直接定义关键字类型为自定义类类型的无序容器。与容器不同,不能直接使用哈希模板,而必须提供我们自己的hash模板版本。

4. Member functions

4.1 constructor、destructor、operator=

4.1.1 constructor

// empty (1)
explicit unordered_set(size_type n ,
					   const hasher& hf = hasher(),
					   const key_equal& eql = key_equal(),
					   const allocator_type& alloc = allocator_type());
explicit unordered_set(const allocator_type& alloc);
// range (2)
template <class InputIterator>
unordered_set(InputIterator first, InputIterator last,
			  size_type n,
			  const hasher& hf = hasher(),
			  const key_equal& eql = key_equal(),
			  const allocator_type& alloc = allocator_type());
// copy (3)
unordered_set(const unordered_set& ust);
unordered_set(const unordered_set& ust, const allocator_type& alloc);
// move (4)
unordered_set(unordered_set&& ust);
unordered_set(unordered_set&& ust, const allocator_type& alloc);
// initializer list (5)
unordered_set(initializer_list<value_type> il,
			  size_type n,
			  const hasher& hf = hasher(),
			  const key_equal& eql = key_equal(),
		  	  const allocator_type& alloc = allocator_type());

// n表示初始桶的最小数量,不是容器中元素的数量

4.1.2 destructor

~unordered_set();

4.1.3 operator= 

// copy (1)
unordered_set& operator=(const unordered_set& ust);
// move (2)
unordered_set& operator=(unordered_set&& ust);
// initializer list (3)
unordered_set& operator=(intitializer_list<value_type> il);

4.2 Capacity

​4.2.1 empty

bool empty() const noexcept;
// 检测unordered_set是否为空,是返回true,否则返回false

4.2.2 size

size_type size() const noexcept;
// 返回unordered_set中元素的个数

4.2.3 max_size

size_type max_size() const noexcept;
// 返回unordered_set能够容纳的最大元素个数

4.3 Iterators

// begin
// container iterator (1)
iterator begin() noexcept;
const_iterator begin() const noexcept;
// bucket iterator (2)
local_iterator begin(size_type n);
const_local_iterator begin(size_type n) const;

// end
// container iterator (1)
iterator end() noexcept;
const_iterator end() const noexcept;
// bucket iterator (2)
local_iterator end(size_type n);
const_local_iterator end(size_type n) const;

// cbegin
// container iterator (1)
const_iterator cbegin() const noexcept;
// bucket iterator (2)
const_local_iterator cbegin(size_type n) const;

// cend
// container iterator (1)
const_iterator cend() const noexcept;
// bucket iterator (2)
const_local_iterator cend(size_type n) const;
函数功能

begin

&

end

(1)版本begin返回一个迭代器,指向unordered_set中第一个元素

(2)版本begin返回一个迭代器,指向unordered_set中桶n的第一个元素

(1)版本end返回一个迭代器,指向unordered_set中最后一个元素的下一个位置

(2)版本end返回一个迭代器,指向unordered_set中桶n的最后一个元素的下一个位置

cbegin

&

cend

(1)版本cbegin返回一个const迭代器,指向unordered_set中第一个元素

(2)版本cbegin返回一个const迭代器,指向unordered_set中桶n的第一个元素

(1)版本cend返回一个const迭代器,指向unordered_set中最后一个元素的下一个位置

(2)版本cend返回一个const迭代器,指向unordered_set中桶n的最后一个元素的下一个位置

#include <unordered_set>
#include <iostream>
using namespace std;

int main()
{
    unordered_set<string> ust{ "iterator","begin","end" };

    cout << "ust contains:" << endl;
    unordered_set<string>::iterator it = ust.begin();
    while (it != ust.end())
    {
        cout << *it << endl;
        ++it;
    }
    // ust contains :
    // iterator
    // begin
    // end

    cout << "ust's buckets contain:" << endl;
    for (int i = 0; i < ust.bucket_count(); ++i)
    {
        cout << "bucket #" << i << " contains:";
        unordered_set<string, string>::local_iterator lit = ust.begin(i);
        while (lit != ust.end(i))
        {
            cout << " " << *lit;
            ++lit;
        }
        cout << endl;
    }
    // ust's buckets contain:
    // bucket #0 contains:
    // bucket #1 contains:
    // bucket #2 contains: end
    // bucket #3 contains:
    // bucket #4 contains:
    // bucket #5 contains:
    // bucket #6 contains: begin
    // bucket #7 contains: iterator

    return 0;
}

4.4 Element lookup

4.4.1 find

iterator find(const key_type& k);
const_iterator find(const key_type& k) const;
// 返回一个迭代器,指向第一个关键字为k的元素,若k不在容器中,则返回end迭代器

4.4.2 count

size_type count(const key_type& k) const;
// 返回关键字等于k的元素的数量
// 对于不允许重复关键字的容器,返回值永远是0或1
#include <unordered_set>
#include <iostream>
using namespace std;

int main()
{
	int arr[5] = { 1,2,6,7,8 };
	unordered_set<int> ust(arr, arr + 5);

	auto it = ust.find(2);
	if (it != ust.end())
	{
		cout << "2在unordered_set中" << endl;
	}
	else
	{
		cout << "2不在unordered_set中" << endl;
	}
	// 2在unordered_set中

	it = ust.find(3);
	if (it != ust.end())
	{
		cout << "3在unordered_set中" << endl;
	}
	else
	{
		cout << "3不在unordered_set中" << endl;
	}
	// 3不在unordered_set中

	if (ust.count(7))
	{
		cout << "7在unordered_set中" << endl;
	}
	else
	{
		cout << "7不在unordered_set中" << endl;
	}
	// 7在unordered_set中

	if (ust.count(5))
	{
		cout << "5在unordered_set中" << endl;
	}
	else
	{
		cout << "5不在unordered_set中" << endl;
	}
	// 5不在unordered_set中

	return 0;
}

4.4.3 equal_range

pair<iterator, iterator> equal_range(const key_type& k);
pair<const_iterator, const_iterator> equal_range(const key_type& k) const;
// 返回一个迭代器pair,表示关键字等于k的元素的范围(左闭右开的区间)
// 若k不存在,pair的两个成员均为end迭代器
// 对于不允许重复关键字的容器,返回的范围最多只包含一个元素

4.5 Modifiers

4.5.1 emplace

template <class... Args> pair<iterator, bool> emplace(Args&&... args);
// 对应insert,区别是:
// 当调用insert时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中
// 当调用emplace时,则是将参数传递给元素类型的构造函数,然后使用这些参数在容器管理的内存空间中直接构造元素

4.5.2 emplace_hint

template <class... Args> iterator emplace_hint(const_iterator position, Args&&... args);
// 对应insert的(3)和(4),区别是:
// 当调用insert时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中
// 当调用emplace时,则是将参数传递给元素类型的构造函数,然后使用这些参数在容器管理的内存空间中直接构造元素

4.5.3 insert

// (1) 成功返回pair<插入位置, true>,失败返回pair<插入位置, false>
pair<iterator, bool> insert(const value_type& val);
// (2)
pair<iterator, bool> insert(value_type&& val);
// (3)
iterator insert(const_iterator hint, const value_type& val);
// (4)
iterator insert(const_iterator hint, value_type&& val);
// (5)
template <class InputIterator> void insert(InputIterator first, InputIterator last);
// (6)
void insert(initializer_list<value_type> il);

// 插入

4.5.4 erase

// by position(1)
iterator erase(const_iterator position);
// by key(2)
size_type erase(const key_type& k);
// range(3)
iterator erase(const_iterator first, const_iterator last);

// 删除

4.5.5 clear

void clear() noexcept;
// 清空

4.5.6 swap

void swap(unordered_set& ust);
// 交换

4.6 Buckets

4.6.1 bucket_count

size_type bucket_count() const noexcept;
// 返回unordered_set中桶的个数

4.6.2 max_bucket_count

size_type max_bucket_count() const noexcept;
// 返回unordered_set能够容纳的最大桶个数

4.6.3 bucket_size

size_type bucket_size(size_type n) const;
// 返回桶n中元素的个数

4.6.4 bucket

size_type bucket(const key_type& k) const;
// 返回关键字为k的元素所在的桶号

4.7 Hash policy

4.7.1 load_factor

float load_factor() const noexcept;
// 返回负载因子(每个桶平均元素的数量,元素的数量/桶的数量)

4.7.2 max_load_factor

// get(1)
float max_load_factor() const noexcept;
// set(2)
void max_load_factor(float z);

// 获取或设置最大负载因子

4.7.3 rehash

void rehash(size_type n);
// 设置桶的数量

4.7.4 reserve

void reserve(size_type n);
// 将桶数设置为最适合包含至少n个元素的桶数

4.8 Observers

4.8.1 hash_function

hasher hash_function() const;
// 返回哈希函数

4.8.2 key_eq

key_equal key_eq() const;
// 返回关键字等价比较谓词

4.8.3 get_allocator

allocator_type get_allocator() const noexcept;
// 返回空间配置器

5. Non-member function overloads

5.1 operators

// equality (1)
template <class Key, class Hash, class Pred, class Alloc>
bool operator==(const unordered_set<Key, Hash, Pred, Alloc>& lhs, const unordered_set<Key, Hash, Pred, Alloc>& rhs);
// inequality (2)
template <class Key, class Hash, class Pred, class Alloc>
bool operator!=(const unordered_set<Key, Hash, Pred, Alloc>& lhs, const unordered_set<Key, Hash, Pred, Alloc>& rhs);

5.2 swap

template <class Key, class Hash, class Pred, class Alloc>
void swap(unordered_set<Key, Hash, Pred, Alloc>& lhs, unordered_set<Key, Hash, Pred, Alloc>& rhs);

6. unordered_set对象的遍历方法

6.1 迭代器

#include <unordered_set>
#include <iostream>
using namespace std;

int main()
{
	int arr[5] = { 1,2,6,7,8 };
	unordered_set<int> ust(arr, arr + 5);

	unordered_set<int>::iterator it = ust.begin();
	while (it != ust.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	// 1 2 6 7 8

	return 0;
}

6.2 范围for

#include <unordered_set>
#include <iostream>
using namespace std;

int main()
{
	int arr[5] = { 1,2,6,7,8 };
	unordered_set<int> ust(arr, arr + 5);

	for (auto& e : ust)
	{
		cout << e << " ";
	}
	cout << endl;
	// 1 2 6 7 8

	return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/388300.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

人工智能时代

一、人工智能发展历史:从概念到现实 人工智能(Artificial Intelligence,简称AI)是计算机科学领域中一门旨在构建能够执行人类智能任务的系统的分支。其发展历程充满曲折,从概念的提出到如今的广泛应用,是技术、理论和实践相互交织的产物。 1. 起源(20世纪中期) 人工智…

代码随想录算法训练营Day27|回溯算法·组合总和、组合总和II、分割回文串

组合总和 class Solution{ private:vector<vector<int>>result;vector<int>path;void backtracking(vector<int>& candidates,int target,int sum,int startIndex){if(sum > target){return;}if(sum target){result.push_back(path);return;}…

混合键合(Hybrid Bonding)工艺解读

随着半导体技术的持续演进&#xff0c;传统的二维芯片缩放规则受到物理极限的挑战&#xff0c;尤其是摩尔定律在微小化方面的推进速度放缓。为了继续保持计算性能和存储密度的增长趋势&#xff0c;业界开始转向三维集成电路设计与封装技术的研发。混合键合技术就是在这样的背景…

【前端实战小项目】学成在线网页制作

文章目录 1.项目准备1.1 项目目录 2.头部区域2.1 头部区域布局2.2 logo制作2.2 导航制作技巧(nav)2.3搜索区域(search)2.3用户区域(user区域) 3.banner区域3.1 总体布局3.2 左侧侧导航(left)3.3 右侧课程表(left) 4.精品推荐区域(recommend)5.精品课程( course)6.前端开发工程师…

MySQL数据库基础(二):MySQL数据库介绍

文章目录 MySQL数据库介绍 一、MySQL介绍 二、MySQL的特点 三、MySQL版本 四、MySQL数据库下载与安装 1、下载 2、安装 五、添加环境变量&#xff08;Windows&#xff09; 六、检测环境变量是否配置成功 MySQL数据库介绍 一、MySQL介绍 MySQL是一个关系型数据库管理…

【Java多线程案例】定时器

1. 定时器简介 定时器&#xff1a;想必大家一定对定时器这个概念不陌生&#xff01;因为它经常出现在我们的日常生活和编程学习中&#xff0c;定时器就好比是一个"闹钟"&#xff0c;会在指定时间处理某件事&#xff08;例如响铃&#xff09;&#xff0c;而在编程世界…

【微服务】skywalking自定义告警规则使用详解

目录 一、前言 二、SkyWalking告警功能介绍 2.1 SkyWalking告警是什么 2.2 为什么需要SkyWalking告警功能 2.2.1 及时发现系统异常 2.2.2 保障和提升系统稳定性 2.2.3 避免数据丢失 2.2.4 提高故障处理效率 三、 SkyWalking告警规则 3.1 SkyWalking告警规则配置 3.2 …

春节结束后如何收心工作?

一、春节结束后的工作准备 春节假期结束后&#xff0c;迎来了新的工作季。在开始新的工作之前&#xff0c;首先需要对即将展开的工作进行充分的准备。整理和清理工作区域&#xff0c;给自己一个干净整洁的工作环境。检查和更新工作日程&#xff0c;确保未来一段时间的工作规划…

删除 Windows 设备和驱动器中的 WPS网盘、百度网盘等快捷图标

在安装诸如WPS软件、百度云盘、爱奇艺等客户端后&#xff0c;Windows 的“我的电脑”&#xff08;或“此电脑”&#xff09;中的“设备和驱动器”部分会出现对应的软件图标。这种情况被许多技术人员视为不必要的干扰&#xff0c;因此许多用户想要知道如何隐藏或删除这些图标。 …

关于保存int型变量进int型数组的做法

如何保存int型变量进int型数组呢&#xff0c;大家先来看看我写的这串代码&#xff1a; #include <bits/stdc.h>using namespace std; int main(){int n;cin >> n;int num;vector<int>a;for (int i 1;i<n;i){cin >> num;if(num % 2 ! 0){a.push_ba…

装饰工程|装饰工程管理系统-项目立项子系统的设计与实现|基于Springboot的装饰工程管理系统设计与实现(源码+数据库+文档)

装饰工程管理系统-项目立项子系统目录 目录 基于Springboot的装饰工程管理系统设计与实现 一、前言 二、系统功能设计 三、系统实现 1、管理员功能实现 &#xff08;2&#xff09;合同报价管理 &#xff08;3&#xff09;装饰材料总计划管理 &#xff08;4&#xff0…

java排课管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 java排课管理系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0&#…

如何将字体添加到 ONLYOFFICE 文档服务器 8.0

作者&#xff1a;VincentYoung 阅读本文&#xff0c;了解如何为自己的在线办公软件 ONLYOFFICE 文档服务器的字体库添加字体 ONLYOFFICE 文档是什么 ONLYOFFICE 文档是一个功能强大的文档编辑器&#xff0c;支持处理文本文档、电子表格、演示文稿、可填写表单、PDF 和电子书…

PR:时间重映射

做一个变换视频速度的效果 原片如下&#xff1a; 现在将跑步的人中间一段加速&#xff0c;后面一段减速 操作如下&#xff1a; 此处点击关键帧时&#xff0c;可以用钢笔工具&#xff0c;也可以按住Ctrl键点击 操作后效果如下&#xff1a;

python-分享篇-五子棋

文章目录 代码效果 代码 """五子棋之人机对战"""import sys import random import pygame from pygame.locals import * import pygame.gfxdraw from checkerboard import Checkerboard, BLACK_CHESSMAN, WHITE_CHESSMAN, offset, PointSIZE 3…

计算机设计大赛 深度学习YOLOv5车辆颜色识别检测 - python opencv

文章目录 1 前言2 实现效果3 CNN卷积神经网络4 Yolov56 数据集处理及模型训练5 最后 1 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; **基于深度学习YOLOv5车辆颜色识别检测 ** 该项目较为新颖&#xff0c;适合作为竞赛课题方向&#xff0…

SpringBoot整合第三方技术-缓存

&#x1f648;作者简介&#xff1a;练习时长两年半的Java up主 &#x1f649;个人主页&#xff1a;程序员老茶 &#x1f64a; ps:点赞&#x1f44d;是免费的&#xff0c;却可以让写博客的作者开心好久好久&#x1f60e; &#x1f4da;系列专栏&#xff1a;Java全栈&#xff0c;…

力扣刷题之旅:高级篇(六)—— 网络流算法:Edmonds-Karp 算法与实际应用

力扣&#xff08;LeetCode&#xff09;是一个在线编程平台&#xff0c;主要用于帮助程序员提升算法和数据结构方面的能力。以下是一些力扣上的入门题目&#xff0c;以及它们的解题代码。 目录 引言 一、Edmonds-Karp 算法简介 二、算法实现 下面是使用 Python 实现的 Edmond…

PKI - 借助Nginx实现_客户端使用自签证书供服务端验证

文章目录 Pre概述在 Nginx 中实现客户端使用自签名证书供服务器验证1. 生成客户端密钥对2. 生成自签名客户端证书3. 配置 Nginx4. 重启 Nginx 修5. 验证 在浏览器中安装客户端证书以便进行访问 Pre PKI - 借助Nginx 实现Https 服务端单向认证、服务端客户端双向认证 PKI - 数…

软件实例分享,洗车店系统管理软件会员卡电子系统教程

软件实例分享&#xff0c;洗车店系统管理软件会员卡电子系统教程 一、前言 以下软件教程以 佳易王洗车店会员管理软件V16.0为例说明 软件文件下载可以点击最下方官网卡片——软件下载——试用版软件下载 1、会员卡号可以绑定车牌号或手机号 2、卡号也可以直接使用手机号&a…