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

unordered_multimap是C++标准库中的一个无序关联容器,允许存储键值对并快速访问。它使用哈希函数来组织元素到桶中,提供平均常数时间复杂度的搜索、插入和删除操作。桶接口包括begin和end方法,用于访问特定桶的首尾元素。示例代码展示了如何插入元素、使用自定义哈希和等价函数以及遍历桶。
定义于头文件 <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_multimap;
(1)(C++11 起)
namespace pmr {

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

}
(2)(C++17 起)

 unordered_multimap 是无序关联容器,支持等价的关键(一个 unordered_multimap 可含有每个关键值的多个副本)和将关键与另一类型的值关联。 unordered_multimap 类支持向前迭代器。搜索、插入和移除拥有平均常数时间复杂度。

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

不要求此容器的迭代顺序稳定(故例如 std::equal 不能用于比较二个 std::unordered_multimap ),除了关键比较等价(以 key_eq() 为比较器比较相等)的每组元素在迭代顺序中组成相接的子范围,它亦可用 equal_range() 访问。

桶接口

返回一个迭代器,指向指定的桶的开始

std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::begin(size_type), 
std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::cbegin(size_type)

local_iterator begin( size_type n );

(C++11 起)

const_local_iterator begin( size_type n ) const;

(C++11 起)

const_local_iterator cbegin( size_type n ) const;

(C++11 起)

 返回指向下标为 n 的桶首元素的迭代器。

参数

n-要访问的桶的下标

返回值

指向首元素的迭代器。

复杂度

常数。

返回一个迭代器,指向指定的桶的末尾

std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::end(size_type), 
std::unordered_multimap<Key,T,Hash,KeyEqual,Allocator>::cend(size_type)

local_iterator end( size_type n );

(C++11 起)

const_local_iterator end( size_type n ) const;

(C++11 起)

const_local_iterator cend( size_type n ) const;

(C++11 起)

返回后随下标为 n 的桶的最后元素的元素的迭代器。此元素表现为占位符,试图访问它会导致未定义行为。

参数

n-要访问的桶的下标

返回值

指向后随最后元素的元素的迭代器。

复杂度

常数

调用示例

#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()
{
    auto generate = []()
    {
        int n = std::rand() % 10 + 110;
        Cell cell{n, n};
        return std::pair<Cell, string>(cell, std::to_string(n));
    };

    std::unordered_multimap<Cell, string, CHash, CEqual> unordered_multimap1;
    //6) 插入来自 initializer_list ilist 的元素。
    while (unordered_multimap1.size() < 5)
    {
        unordered_multimap1.insert({generate()});
    }

    std::cout << "unordered_multimap1:   ";
    std::copy(unordered_multimap1.begin(), unordered_multimap1.end(),
              std::ostream_iterator<pair<Cell, string>>(std::cout, " "));
    std::cout << std::endl;
    std::cout << std::endl;

    for (std::unordered_multimap<Cell, string, CHash, CEqual>::const_iterator cit =
                unordered_multimap1.cbegin(); cit != unordered_multimap1.end(); cit++)
    {
        //返回关键 key 的桶的下标。始终会在此桶中找到关键等于 key 的元素(若存在)。
        //返回值仅对 bucket_count() 返回相同值的容器实例合法。
        size_t bucket = unordered_multimap1.bucket(cit->first);
        std::cout << "unordered_multimap1 bucket(" << cit->first << ") :    "
                  << bucket << "    ";

        //返回指向下标为 n 的桶首元素的迭代器。
        std::unordered_multimap<Cell, string, CHash, CEqual>::const_local_iterator clit
            = unordered_multimap1.begin(bucket);
        std::cout << "const_local_iterator begin(" << bucket << "):    " << *clit << std::endl;
    }
    std::cout << std::endl;


    for (std::unordered_multimap<Cell, string, CHash, CEqual>::const_iterator cit =
                unordered_multimap1.cbegin(); cit != unordered_multimap1.end(); cit++)
    {
        //返回关键 key 的桶的下标。始终会在此桶中找到关键等于 key 的元素(若存在)。
        //返回值仅对 bucket_count() 返回相同值的容器实例合法。
        size_t bucket = unordered_multimap1.bucket(cit->first);
        std::cout << "unordered_multimap1 bucket(" << cit->first << ") :    "
                  << bucket << "    ";

        //返回指向下标为 n 的桶首元素的迭代器。
        std::unordered_multimap<Cell, string, CHash, CEqual>::local_iterator clit =
            unordered_multimap1.begin(bucket);
        std::cout << "local_iterator begin(" << bucket << "):    " << *clit << std::endl;
    }
    std::cout << std::endl;


    for (std::unordered_multimap<Cell, string, CHash, CEqual>::const_iterator cit =
                unordered_multimap1.cbegin(); cit != unordered_multimap1.end(); cit++)
    {
        //返回关键 key 的桶的下标。始终会在此桶中找到关键等于 key 的元素(若存在)。
        //返回值仅对 bucket_count() 返回相同值的容器实例合法。
        size_t bucket = unordered_multimap1.bucket(cit->first);
        std::cout << "unordered_multimap1 bucket(" << cit->first << ") :    "
                  << bucket << "    ";

        //返回指向下标为 n 的桶首元素的迭代器。
        std::unordered_multimap<Cell, string, CHash, CEqual>::const_local_iterator clit =
            unordered_multimap1.cbegin(bucket);
        std::cout << "const_local_iterator cbegin(" << bucket << "):    " << *clit << std::endl;
    }

    return 0;
}

输出

 

<think>首先,用户的问题是关于C++标准库中的容器:用户想确认哈希Map是否对应std::unordered_map,而STL Map是否对应std::map。 从系统级指令中,我知道: - 所有行内数学表达式必须使用$...$格式。 - 独立公式必须使用$$...$$格式并单独成段。 - 使用LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如[^1]。 - 回答结构清晰,帮助用户逐步解决问题。 - 参考站内引用:用户提供了三个引用,我需要参考这些引用,但用户说“上述引用仅供参考,并不是用户真正的需求”,所以我应该基于用户的问题来回答,但可以引用这些内容来支持我的回答。 用户的问题:"我想确认哈希Map和STL Map在C++标准库中的对应实现 请问哈希 Map 是否对应 C++ 标准库中的 std::unordered_map,而 STL Map 是否对应 std::map" 从引用中: - 引用[1]:提到std::map, std::multimap, std::unordered_map是关联容器。 - 引用[2]:详细比较了std::map(基于红黑树)和std::unordered_map(基于哈希表)。它说std::map是有序的,时间复杂度O(log n),而std::unordered_map查找效率O(1),但内存占用高。 - 引用[3]:关于std::unordered_map的C++11标准模板。 所以,用户的问题很简单:哈希Map对应std::unordered_map,STL Map对应std::map。这在C++中是标准术语。 回答结构: 1. **确认问题**:直接回答用户的疑问。 2. **解释细节**:简要解释为什么,基于引用或标准知识。 3. **生成相关问题**:在回答末尾添加相关问题部分,就像示例中那样。 使用中文回答。 生成相关问题:基于主题,生成2-3个相关问题,例如: - 哈希表和红黑树的区别? - 何时使用std::map vs std::unordered_map? - std::map和std::unordered_map的性能比较? 引用标识:在回答中,如果引用内容,添加[^1]等。但用户提供的引用是站内的,所以我可以在解释时引用它们。 例如:如引用[2]所述,std::map基于红黑树... 但用户说“请尽可能多的参考用户上一次的问题和你的回答”,但这是第一次交互,所以没有上一次问题。直接基于当前问题。 最终回答结构: - 开头:直接确认答案。 - 主体:解释细节,使用清晰的结构。 - 结尾:添加相关问题部分。 数学表达式:用户的问题不涉及数学,但如果有,要使用正确格式。这里可能不需要数学表达式,除非提到时间复杂度,比如O(log n)可以用行内数学。 例如:时间复杂度为$O(\log n)$。 确保LaTeX正确。</think>### 哈希Map和STL Map在C++标准库中的对应实现 是的,您的理解完全正确。在C++标准库中: - **哈希Map(Hash Map)** 对应 **std::unordered_map**。这个容器基于哈希表(Hash Table)实现,提供了平均常数时间复杂度的查找、插入和删除操作(即$O(1)$),但不保证元素的有序性。它适用于需要高效查找但对元素顺序不敏感的场景[^2]。 - **STL Map(Standard Template Library Map)** 对应 **std::map**。这个容器基于红黑树(Red-Black Tree)实现,是一种自平衡二叉搜索树,保证了元素按键的有序存储(升序排列)。查找、插入和删除操作的时间复杂度为$O(\log n)$,适用于需要有序数据或对内存占用敏感的情况[^1][^2]。 #### 详细解释 - **std::unordered_map 的特点**: 它使用哈希函数将键映射到(buckets)中,实现快速访问。但哈希表可能导致哈希冲突,影响性能(最坏情况为$O(n)$)。另外,它不支持直接遍历有序元素,因为存储顺序取决于哈希值。内存占用较高,需要预分配空间来存储散列表[^2][^3]。例如,在C++11中,std::unordered_map的定义包括键类型、值类型、哈希函数和相等比较器: ```cpp 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; ``` - **std::map 的特点**: 它基于红黑树,数据始终保持有序(按键排序),支持范围查询和迭代器遍历(效率高)。虽然时间复杂度为$O(\log n)$,但内存占用相对较低,因为它不需要额外的哈希表结构。但相比哈希表,查找速度在大型数据集上可能稍慢[^1][^2]。 #### 为什么这样对应? - 哈希Map的核心是哈希表,而std::unordered_map正是C++标准库中基于哈希表的实现。 - STL Map通常指的是有序映射,std::map使用树结构保证有序性,这是C++中传统的“Map”容器。 如引用[2]所述,红黑树(std::map)和哈希表(std::unordered_map)在性能和内存上各有优劣:哈希表查找快但内存高,红黑树有序但操作稍慢。 #### 选择建议 - 使用 **std::unordered_map** 当: 需要高效查找(如缓存、字典),数据量大,且不关心顺序。 - 使用 **std::map** 当: 需要有序数据(如排序输出),内存有限,或涉及频繁的范围查询(如区间搜索)。 如果您有具体代码示例或性能需求,我可以进一步分析优化方案!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值