c++11 标准模板(STL)(std::unordered_set)(二)

news2024/9/22 5:25:08
定义于头文件 <unordered_set>
template<

    class Key,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator<Key>

> class unordered_set;
(1)(C++11 起)
namespace pmr {

    template <class Key,
              class Hash = std::hash<Key>,
              class Pred = std::equal_to<Key>>
    using unordered_set = std::unordered_set<Key, Hash, Pred,
                                             std::pmr::polymorphic_allocator<Key>>;

}
(2)(C++17 起)

unordered_set is 是含有 Key 类型唯一对象集合的关联容器。搜索、插入和移除拥有平均常数时间复杂度。

在内部,元素并不以任何特别顺序排序,而是组织进桶中。元素被放进哪个桶完全依赖其值的哈希。这允许对单独元素的快速访问,因为哈希一旦,就准确指代元素被放入的桶。

不可修改容器元素(即使通过非 const 迭代器),因为修改可能更改元素的哈希,并破坏容器。

 

成员函数

构造 unordered_set

std::unordered_set<Key,Hash,KeyEqual,Allocator>::unordered_set
unordered_set() : unordered_set( size_type(/*implementation-defined*/) ) {}

explicit unordered_set( size_type bucket_count,
                        const Hash& hash = Hash(),
                        const key_equal& equal = key_equal(),

                        const Allocator& alloc = Allocator() );
(1)(C++11 起)
unordered_set( size_type bucket_count,

               const Allocator& alloc )
              : unordered_set(bucket_count, Hash(), key_equal(), alloc) {}
unordered_set( size_type bucket_count,
               const Hash& hash,
               const Allocator& alloc )

              : unordered_set(bucket_count, hash, key_equal(), alloc) {}
(1)(C++14 起)

explicit unordered_set( const Allocator& alloc );

(1)(C++11 起)
template< class InputIt >

unordered_set( InputIt first, InputIt last,
               size_type bucket_count = /*implementation-defined*/,
               const Hash& hash = Hash(),
               const key_equal& equal = key_equal(),

               const Allocator& alloc = Allocator() );
(2)(C++11 起)
template< class InputIt >

unordered_set( InputIt first, InputIt last,
               size_type bucket_count,
               const Allocator& alloc )
              : unordered_set(first, last,

                  bucket_count, Hash(), key_equal(), alloc) {}
(2)(C++14 起)
template< class InputIt >

unordered_set( InputIt first, InputIt last,
               size_type bucket_count,
               const Hash& hash,
               const Allocator& alloc )
              : unordered_set(first, last,

                  bucket_count, hash, key_equal(), alloc) {}
(2)(C++14 起)

unordered_set( const unordered_set& other );

(3)(C++11 起)

unordered_set( const unordered_set& other, const Allocator& alloc );

(3)(C++11 起)

unordered_set( unordered_set&& other );

(4)(C++11 起)

unordered_set( unordered_set&& other, const Allocator& alloc );

(4)(C++11 起)
unordered_set( std::initializer_list<value_type> init,

               size_type bucket_count = /*implementation-defined*/,
               const Hash& hash = Hash(),
               const key_equal& equal = key_equal(),

               const Allocator& alloc = Allocator() );
(5)(C++11 起)
unordered_set( std::initializer_list<value_type> init,

               size_type bucket_count,
               const Allocator& alloc )
              : unordered_set(init, bucket_count,

                  Hash(), key_equal(), alloc) {}
(5)(C++14 起)
unordered_set( std::initializer_list<value_type> init,

               size_type bucket_count,
               const Hash& hash,
               const Allocator& alloc )
              : unordered_set(init, bucket_count,

                  hash, key_equal(), alloc) {}
(5)(C++14 起)

从各种数据源构造新容器。可选的以用户提供的 bucket_count 为用于创建的最小桶数,以 hash 为哈希函数,以 equal 为比较关键的函数,和以 alloc 为分配器。

1) 构造空容器。设置 max_load_factor() 为 1.0 。对于默认构造函数,桶数是实现定义的。

2) 构造拥有范围 [first, last) 的内容的容器。设置 max_load_factor() 为 1.0 。若范围中的多个元素拥有比较等价的关键,则插入哪个元素是未指定的(待决的 LWG2844 )。

3) 复制构造函数。构造拥有 other 内容副本的容器,一同复制加载因子、谓词和哈希函数。若不提供 alloc ,则通过调用 std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator()) 获得分配器。

4) 移动构造函数。用移动语义构造拥有 other 内容的容器。若不提供 alloc ,则通过从属于 other 的分配器移动构造获得分配器。

5) 构造拥有 initializer_list init 内容的容器,同 unordered_set(init.begin(), init.end()) 。

参数

alloc-用于此容器所有内存分配器的分配器
bucket_count-初始化时用的最小桶数。若不指定,则使用实现定义的默认值
hash-要用的哈希函数
equal-用于此容器所有关键比较的比较函数
first, last-复制元素来源的范围
other-用作源以初始化容器元素的另一容器
init-用以初始化容器元素的 initializer_list
类型要求
- InputIt 必须满足遗留输入迭代器 (LegacyInputIterator) 的要求。

复杂度

1) 常数

2) 平均情况与 firstlast 间的距离成线性,最坏情况成平方。

3) 与 other 的大小成线性。

4) 常数。若给定 alloc 且 alloc != other.get_allocator() 则为线性。

5) 平均情况与 init 的大小成线性,最坏情况成平方。

异常

Allocator::allocate 的调用可能抛出。

注意

在容器移动构造(重载 (4) )后,指向 other 的引用及迭代器(除了尾迭代器)保持合法,但指代现于 *this 中的元素。当前标准由 [container.requirements.general]/12 中的总括陈述作出此保证,而 LWG 2321 正在考虑更严格的保证。

析构 unordered_set

std::unordered_set<Key,Hash,KeyEqual,Allocator>::~unordered_set

~unordered_set();

(C++11 起)

销毁容器。调用元素的析构函数,然后解分配所用的存储。注意,若元素是指针,则不销毁所指向的对象。

复杂度

与容器大小成线性。

调用示例

#include <iostream>
#include <forward_list>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <unordered_set>
#include <time.h>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell() = default;
    Cell(int a, int b): x(a), y(b) {}

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator +(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator *(const Cell &cell)
    {
        x *= cell.x;
        y *= cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }


    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator >(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y > cell.y;
        }
        else
        {
            return x > cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

struct myCompare
{
    bool operator()(const int &a, const int &b)
    {
        return a < b;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

std::ostream &operator<<(std::ostream &os, const std::pair<const int, Cell> &pCell)
{
    os << pCell.first << "-" << pCell.second;
    return os;
}

struct CHash
{
    size_t operator()(const Cell& cell) const
    {
        size_t thash = std::hash<int>()(cell.x) | std::hash<int>()(cell.y);
//        std::cout << "CHash: " << thash << std::endl;
        return thash;
    }
};

struct CEqual
{
    bool operator()(const Cell &a, const Cell &b) const
    {
        return a.x == b.x && a.y == b.y;
    }
};

int main()
{
    std::cout << std::boolalpha;

    std::mt19937 g{std::random_device{}()};
    srand((unsigned)time(NULL));

    auto generate = []()
    {
        int n = std::rand() % 10 + 100;
        Cell cell{n, n};
        return cell;
    };

    //1) 构造空容器。设置 max_load_factor() 为 1.0 。对于默认构造函数,桶数是实现定义的。
    std::unordered_set<Cell, CHash, CEqual> unordered_set1;
    std::cout << "unordered_set1 is empty " << unordered_set1.empty() << std::endl;
    std::cout << std::endl;


    std::vector<Cell> vector1(6);
    std::generate(vector1.begin(), vector1.end(), generate);
    std::cout << "vector1:          ";
    std::copy(vector1.begin(), vector1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    //2) 构造拥有范围 [first, last) 的内容的容器。
    //设置 max_load_factor() 为 1.0 。若范围中的多个元素拥有比较等价的关键,则插入哪个元素是未指定的。
    std::unordered_set<Cell, CHash, CEqual> unordered_set2(vector1.begin(), vector1.end());
    std::cout << "unordered_set2:   ";
    std::copy(unordered_set2.begin(), unordered_set2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    //3) 复制构造函数。构造拥有 other 内容副本的容器,一同复制加载因子、谓词和哈希函数。
    std::unordered_set<Cell, CHash, CEqual> unordered_set3(unordered_set2);
    std::cout << "unordered_set3:   ";
    std::copy(unordered_set3.begin(), unordered_set3.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    //4) 移动构造函数。用移动语义构造拥有 other 内容的容器。
    //若不提供 alloc ,则通过从属于 other 的分配器移动构造获得分配器。
    std::unordered_set<Cell, CHash, CEqual> unordered_set4(std::move(unordered_set2));
    std::cout << "unordered_set4:   ";
    std::copy(unordered_set4.begin(), unordered_set4.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    //5) 构造拥有 initializer_list init 内容的容器,同 unordered_set(init.begin(), init.end()) 。
    std::unordered_set<Cell, CHash, CEqual> unordered_set5
    {generate(), generate(), generate(), generate(), generate(), generate()};
    std::cout << "unordered_set5:   ";
    std::copy(unordered_set5.begin(), unordered_set5.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}

输出

 

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

python中的for循环以及枚举函数enumerate()

一、可迭代的对象&#xff08;iteratle_object&#xff09; python中可以使用for循环进行迭代的对象大致有以下几种类型&#xff1a; String(字符串)List(列表)Tuple(元组)Dictionary(字典)range()内置函数返回的对象 二、for循环迭代示例 1. 依次输出字符串"python&q…

printk浅析

内核printk原理介绍 - 知乎 (zhihu.com)34.Linux-printk分析、使用prink调试驱动 (bbsmax.com)【原创】计算机自制操作系统(Linux篇)五&#xff1a;内核开发之万丈高楼从地起---printk(理清pintf/vprintf&#xff1b;sprintf/vsprintf &#xff1b;fprintf/vfprintf) - 知乎 (z…

自抗扰控制ADRC之扩张观测器

目录 前言 1. 被控对象(被观测对象) 2.非线性观测器 2.1仿真分析 2.2仿真模型 2.3仿真结果 3.线性观测器 3.1仿真模型 3.2仿真结果 4.总结和学习问题 前言 什么叫观测器&#xff1f;为什么该类观测称为扩张观测器&#xff1f; &#xff1a;观测器可以理解为所观测…

组合数学原理与例题

目录 一、前言 二、计数原理 1、加法原理 2、分割立方体&#xff08;lanqiaoOJ题号1620&#xff09; 3、乘法原理 4、挑选子串&#xff08;lanqiaoOJ题号1621&#xff09; 5、糊涂人寄信&#xff08;lanqiaoOJ题号1622&#xff09; 6、战斗吧N皇后&#xff08;lanqiaoO…

依次判断数组1对中的每个元素是否小于等于数组2中对应位置的每个元素numpy.less_equal()

【小白从小学Python、C、Java】【计算机等级考试500强双证书】 【Python-数据分析】 依次判断数组1对中的每个元素是否 小于等于数组2中对应位置的每个元素 numpy.less_equal() [太阳]选择题 以下错误的一项是? import numpy as np a np.array([1,2,3]) b np.array([1,3,2]) …

kubernetes 核心技术-Pod(1)

概述&#xff1a; 首先要知道 Pod 不是容器&#xff01; 一、 基本概念 Pod 是 k8s 系统中可以创建和管理的最小单元。k8s 不会直接处理容器&#xff0c;而是podpod 包含多个容器(一组容器的集合)一个pod中容器共享网络命名空间pod是短暂的(生命周期) 二、Pod存在的意义 创建…

数据结构与算法总结整理(超级全的哦!)

数据结构与算法基础大O表示法时间复杂度大O表示法时间复杂度排序&#xff1a;最坏时间复杂度时间复杂度的几条基本计算规则内存工作原理什么是内存内存主要分为三种存储器随机存储器&#xff08;RAM&#xff09;只读存储器&#xff08;ROM&#xff09;高速缓存&#xff08;Cach…

玄子Share-BCSP助学手册-JAVA开发

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b2gPyAnt-1676810001349)(./assets/%E7%8E%84%E5%AD%90Share%E4%B8%89%E7%89%88.jpg)] 玄子Share-BCSP助学手册-JAVA开发 前言&#xff1a; 此文为玄子&#xff0c;复习BCSP一二期后整理的文章&#x…

多任务学习综述Multi-Task Deep Recommender Systems

Multi-Task Deep Recommender Systems: A Survey 最近看到一篇多任务学习的综述&#xff0c;觉得总结的不错&#xff0c;记录一下。 1. 简介 推荐系统天然具有多任务学习的需求&#xff0c;以视频推荐为例&#xff0c;用户具有点赞、评论、转发等不同的行为。多任务学习相比…

“生成音乐“ 【循环神经网络】

前言 本文介绍循环神经网络的进阶案例&#xff0c;通过搭建和训练一个模型&#xff0c;来对钢琴的音符进行预测&#xff0c;通过重复调用模型来进而生成一段音乐&#xff1b; 使用到Maestro的钢琴MIDI文件 &#xff0c;每个文件由不同音符组成&#xff0c;音符用三个量来表示…

千锋教育嵌入式物联网教程之系统编程篇学习-04

目录 alarm函数 raise函数 abort函数 pause函数 转折点 signal函数 可重入函数 信号集 sigemptyset() sigfillset sigismember()​ sigaddset()​ sigdelset()​ 代码讲解 信号阻塞集 sigprocmask()​ alarm函数 相当于一个闹钟&#xff0c;默认动作是终止调用alarm函数的进…

HSCSEC 2023 个人练习

&#x1f60b; 大家好&#xff0c;我是YAy_17&#xff0c;是一枚爱好网安的小白。本人水平有限&#xff0c;欢迎各位大佬指点&#xff0c;欢迎关注&#x1f601;&#xff0c;一起学习 &#x1f497; &#xff0c;一起进步 ⭐ 。⭐ 此后如竟没有炬火&#xff0c;我便是唯一的光。…

聊一聊国际化i18n

i18n 概述i18n 是国际化的缩写&#xff0c;其完整的写法是 Internationalization&#xff0c;翻译为国际化。国际化是指在软件开发中对于不同语言和地区的支持。目的是为了让一款软件可以在不同的语言和地区环境下正常运行&#xff0c;使其适应全球各地的用户。这通常包括对语言…

Simulink 自动代码生成电机控制:低阶滑模观测器仿真实现及生成代码在开发板上运行

目录 理论参考 仿真实现 运行演示 总结 前段实时搭过高阶的滑模观测器&#xff0c;相比于高阶的&#xff0c;普通的滑模观测器计算量小更适合计算能力低的MCU&#xff0c;这里参考Microchip的16位MCU所使用的观测器&#xff0c;通过Simulink建模仿真实现系统控制&#xff0…

【查看多个长图】如何方便地在安卓手机上查看多个长图?如何更便捷地浏览长图合集

经常我会看到有些知识分享是通过长图形式进行。 往往在手机本地的图片浏览器中不能很方便地查看很多长图&#xff08;能放大&#xff0c;但是横向滑动时&#xff0c;无法保证同样的放缩比例浏览同一个文件夹&#xff09;。 我推荐下面一个APP和曲折解决办法。 1、perfect vi…

Error: Timeout trying to fetch resolutions from npm

总目录&#xff1a; 如何使用VSCode插件codesight扫描出前端项目的风险依赖包并借助 npm-force-resolutions 修复之&#xff1f;blackduck issue fix 文章目录问题描述【最终解决】我搜索到的解决方案npmjs 该依赖各版本列表及对应的被下载次数github issue 说降级到0.0.3就可以…

(十五)、从插件市场引入问题反馈页面【uniapp+uinicloud多用户社区博客实战项目(完整开发文档-从零到完整项目)】

1&#xff0c;插件市场问题反馈页面 插件市场链接 dloud插件插件市场中找到问题反馈插件&#xff1a; 首先确保登录了dcloud账号。 使用hbuilderX导入插件到自己项目中。 选择合并导入。 从插件市场导入意见反馈页面的路径地址如下&#xff1a; 2&#xff0c;点击跳转到…

论文阅读_AlphaGo_Zero

论文信息 name_en: Mastering the game of Go without human knowledge name_ch: 在没有人类知识的情况下掌握围棋游戏 paper_addr: http://www.nature.com/articles/nature24270 doi: 10.1038/nature24270 date_publish: 2017-10-01 tags: [‘深度学习’,‘强化学习’] if: 6…

【C++封装】C++面向对象模型

文章内容如下&#xff1a; 1&#xff09;成员变量和函数的存储 2&#xff09;this指针 3&#xff09;const修饰成员函数 4&#xff09;有元 一。成员变量和函数的存储 C实现了封装&#xff0c;数据(-变量)和处理数据的操作(-函数)是分开存储的&#xff0c;C中的非静态数据…

SpringBoot Notes

文章目录1 SpringBootWeb快速入门1.1Spring官网1.2 Web分析2. HTTP协议2.1 HTTP介绍34 SpringBootWeb请求响应5 响应6 分层解耦6.1 三层架构6.1.1 三层架构介绍6.1.2 基于三层架构的程序执行流程&#xff1a;6.1.3 代码拆分6.2 分层解耦6.2.1 内聚、耦合6.2.2 解耦思路6.3 IOC&…