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

本文详细介绍了C++标准库中的unordered_map容器,它是一个基于哈希表的关联容器,提供了高效的搜索、插入和删除操作。unordered_map的构造函数有多种重载形式,允许用户自定义桶的数量、哈希函数、比较函数以及分配器。文章还展示了通过不同方式构造unordered_map的实例,并给出了相应的代码示例。
摘要由CSDN通过智能技术生成
定义于头文件 <unordered_map>
template<

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

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

    template <class Key,
              class T,
              class Hash = std::hash<Key>,
              class KeyEqual = std::equal_to<Key>>
              using unordered_map = std::unordered_map<Key, T, Hash, Pred,
                              std::pmr::polymorphic_allocator<std::pair<const Key,T>>>;

}
(2)(C++17 起)

 unordered_map 是关联容器,含有带唯一键的键-值 pair 。搜索、插入和元素移除拥有平均常数时间复杂度。

元素在内部不以任何特定顺序排序,而是组织进桶中。元素放进哪个桶完全依赖于其键的哈希。这允许对单独元素的快速访问,因为一旦计算哈希,则它准确指代元素所放进的桶。

成员函数

构造 unordered_map

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

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

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

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

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

explicit unordered_map( const Allocator& alloc );

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

unordered_map( 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_map( InputIt first, InputIt last,
               size_type bucket_count,
               const Allocator& alloc )
              : unordered_map(first, last,

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

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

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

unordered_map( const unordered_map& other );

(3)(C++11 起)

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

(3)(C++11 起)

unordered_map( unordered_map&& other );

(4)(C++11 起)

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

(4)(C++11 起)
unordered_map( 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_map( std::initializer_list<value_type> init,

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

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

               size_type bucket_count,
               const Hash& hash,
               const Allocator& alloc )
              : unordered_map(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_map(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_map

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::~unordered_map

~unordered_map();

(C++11 起)

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

复杂度

与容器大小成线性。

调用示例

 

#include <iostream>
#include <forward_list>
#include <string>
#include <iterator>
#include <algorithm>
#include <functional>
#include <unordered_map>
#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<Cell, string> &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 + 110;
        Cell cell{n, n};
        return std::pair<Cell, string>(cell, std::to_string(n));
    };

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

    std::unordered_map<Cell, string, CHash, CEqual> unordered_map6(6);
    std::cout << "unordered_map6 is empty " << unordered_map6.empty()
              << "  bucket_count:   " << unordered_map6.bucket_count() << std::endl;
    std::cout << std::endl;

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


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

    std::unordered_map<Cell, string, CHash, CEqual> unordered_map7(vector1.begin(), vector1.end(), 8);
    std::cout << "unordered_map7 size:  " << unordered_map7.size()
              << "  bucket_count:   " << unordered_map7.bucket_count() << std::endl;
    std::cout << "unordered_map7:   ";
    std::copy(unordered_map7.begin(), unordered_map7.end(), std::ostream_iterator<std::pair<Cell, string>>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;


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


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


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

    std::unordered_map<Cell, string, CHash, CEqual> unordered_map8
    ({generate(), generate(), generate(), generate(), generate(), generate()}, 8);
    std::cout << "unordered_map8 size:  " << unordered_map8.size()
              << "  bucket_count:   " << unordered_map8.bucket_count() << std::endl;
    std::cout << "unordered_map8:   ";
    std::copy(unordered_map8.begin(), unordered_map8.end(), std::ostream_iterator<std::pair<Cell, string>>(std::cout, " "));
    std::cout << std::endl;
    return 0;
}

输出

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值