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

定义于头文件 <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 迭代器),因为修改可能更改元素的哈希,并破坏容器。

修改器

原位构造元素

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

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

(C++11 起)

若容器中无拥有该关键的元素,则插入以给定的 args 原位构造的新元素到容器。

细心地使用 emplace 允许在构造新元素的同时避免不必要的复制或移动操作。 准确地以与提供给 emplace 者相同的参数,通过 std::forward<Args>(args)... 转发调用新元素的构造函数。 即使容器中已有拥有该关键的元素,也可能构造元素,该情况下新构造的元素将被立即销毁。

若因插入发生重哈希,则所有迭代器都被非法化。否则迭代器不受影响。引用不被非法化。重哈希仅若新元素数量大于 max_load_factor()*bucket_count() 才发生。

参数

args-要转发给元素构造函数的参数

返回值

返回由指向被插入元素,或若不发生插入则为既存元素的迭代器,和指代插入是否发生的 bool (若发生插入则为 true ,否则为 false )。

异常

若任何操作抛出异常,则此函数无效果。

复杂度

平均为均摊常数,最坏情况与容器大小成线性。

使用提示原位构造元素

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

template <class... Args>
iterator emplace_hint( const_iterator hint, Args&&... args );

(C++11 起)

插入新元素到容器,以 hint 为放置元素位置的建议。原位构造元素,即不进行复制或移动操作。

准确地以提供给函数的参数相同者,以 std::forward<Args>(args)... 转发调用元素的构造函数。

若因插入发生重哈希,则所有迭代器都被非法化。否则迭代器不受影响。引用不被非法化。重哈希仅若新元素数量大于 max_load_factor()*bucket_count() 才发生。

参数

hint-迭代器,用作插入新元素位置的建议
args-转发给元素构造函数的参数

返回值

指向新插入元素的迭代器。

若因元素已存在而失败,则返回指向拥有等价关键的既存元素。

异常

若任何操作抛出异常,则此函数无效果(强异常保证)。

复杂度

平均为均摊常数,最坏情况下与容器大小成线性。

交换内容

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

void swap( unordered_set& other );

(C++11 起)
(C++17 前)

void swap( unordered_set& other ) noexcept(/* see below */);

(C++17 起)

将内容与 other 的交换。不在单个元素上调用任何移动、复制或交换操作。

所有迭代器和引用保持合法。尾后迭代器被非法化。

HashKeyEqual 对象必须可交换 (Swappable) ,并用非成员 swap 的非限定调用交换它们。

若 std::allocator_traits<allocator_type>::propagate_on_container_swap::value 为 true ,则用非成员 swap 的非限定调用交换分配器。否则,不交换它们(且若 get_allocator() != other.get_allocator() ,则行为未定义)。

(C++11 起)

参数

other-要与之交换内容的容器

返回值

(无)

异常

任何 HashKeyEqual 对象交换所抛的异常。

(C++17 前)
noexcept 规定:  noexcept(std::allocator_traits<Allocator>::is_always_equal::value

&& std::is_nothrow_swappable<Hash>::value

&& std::is_nothrow_swappable<key_equal>::value)
(C++17 起)

复杂度

常数。

调用示例

#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;
    };

    std::unordered_set<Cell, CHash, CEqual> unordered_set1;
    for (size_t index = 0; index < 5; index++)
    {
        //若容器中无拥有该关键的元素,则插入以给定的 args 原位构造的新元素到容器。
        std::pair<std::unordered_set<Cell, CHash, CEqual>::iterator, bool> iit
            = unordered_set1.emplace(std::rand() % 10 + 100, std::rand() % 10 + 100);
        std::cout << "unordered_set1 emplace : " << *iit.first << "   " << iit.second << std::endl;
    }
    std::cout << "unordered_set1:   ";
    std::copy(unordered_set1.begin(), unordered_set1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;


    std::unordered_set<Cell, CHash, CEqual> unordered_set2;
    for (size_t index = 0; index < 5; index++)
    {
        //3-4) 插入 value ,以 hint 为应当开始搜索的位置的非强制建议。
        std::unordered_set<Cell, CHash, CEqual>::iterator iit
            = unordered_set2.emplace_hint(unordered_set2.cbegin(),
                                          std::rand() % 10 + 100, std::rand() % 10 + 100);
        std::cout << "unordered_set2 insert : " << *iit  << std::endl;
    }
    std::cout << "unordered_set2:   ";
    std::copy(unordered_set2.begin(), unordered_set2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;


    //将内容与 other 的交换。不在单个元素上调用任何移动、复制或交换操作。
    unordered_set2.swap(unordered_set1);
    std::cout << "after swap:   " << std::endl;
    std::cout << "unordered_set1:   ";
    std::copy(unordered_set1.begin(), unordered_set1.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << "unordered_set2:   ";
    std::copy(unordered_set2.begin(), unordered_set2.end(), std::ostream_iterator<Cell>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;

    return 0;
}

输出

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值