为什么std::map接受std::对作为键,而std::unordered_map不接受呢? [英] Why does std::map accept a std::pair as key, but std::unordered_map does not?

查看:146
本文介绍了为什么std::map接受std::对作为键,而std::unordered_map不接受呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在考虑复制之前,请了解我的问题的基础。

为什么C++std::map接受std::pair作为键类型,而std::unordered_map不接受?

第一个案例编译完美:

#include <map>
#include <utility>

using namespace std;

typedef pair<int,int> int_pair;

int main()
{
    map<int_pair,int> m;

    return 0;
}

第二种情况会产生大量编译错误。从this SO questionthis SO question可以清楚地看出,必须创建自定义哈希函数和等价运算符。

#include <unordered_map>
#include <utility>

using namespace std;

typedef pair<int,int> int_pair;

int main()
{
    unordered_map<int_pair,int> m;

    return 0;
}

此处的问题不是如何为std::unordered_map编写哈希函数。问题是,当std::map不需要时,为什么还需要一个呢?

我知道std::map是二叉搜索树(BST),但是在非基本类型(Int_Pair)的键之间究竟进行了怎样的比较?

推荐答案

std::map不散列任何内容。它使用std::less作为其默认比较器。它将适用于支持operator<的任何类型。

std::unordered_map使用std::hash提供的哈希对其元素进行排序。

碰巧std::pair提供operator<,但没有std::hash的专门化。

这篇关于为什么std::map接受std::对作为键,而std::unordered_map不接受呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆