C ++ unordered_map具有pair作为键 - 不编译 [英] C++ unordered_map with pair as key - not compiling

查看:416
本文介绍了C ++ unordered_map具有pair作为键 - 不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个unordered_map来映射具有整数的对。

I am trying to create an unordered_map to map pairs with integers.

#include <unordered_map>

using namespace std;
using Vote = pair<string, string>;
using Unordered_map = unordered_map<Vote, int>;

我有一个类,我已经宣布Unordered_map为私有成员。

I have a class where I have declared an Unordered_map as a private member.

但是,我尝试编译时收到此错误:

However, I am getting this error when I try to compile:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/type_traits:948:38: Implicit instantiation of undefined template 'std::__1::hash<std::__1::pair<std::__1::basic_string<char>, std::__1::basic_string<char> > >'

如果我使用常规地图,如

I am not getting this error if I use a regular map like map<pair<string, string>, int> instead of an unordered_map.

无法使用

Is it not possible to use pair as key in unordered maps?

推荐答案

键类型。一个简单的例子:

You need to provide a suitable hash function for your key type. A simple example:

#include <unordered_map>
#include <functional>
#include <string>
#include <utility>

// Only for pairs of std::hash-able types for simplicity.
// You can of course template this struct to allow other hash functions
struct pair_hash {
    template <class T1, class T2>
    std::size_t operator () (const std::pair<T1,T2> &p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;  
    }
};

using namespace std;
using Vote = pair<string, string>;
using Unordered_map = unordered_map<Vote, int, pair_hash>;

int main() {
    Unordered_map um;
}

这将工作,但没有最好的哈希属性。您可能需要查看类似 boost.hash_combine 在组合散列时获得更高质量的结果。

This will work, but not have the best hash-properties. You might want to have a look at something like boost.hash_combine for higher quality results when combining the hashes.

对于现实世界使用:Boost还提供函数集 hash_value 已经为 std :: pair 以及 std :: tuple 和大多数标准容器。

For real world use: Boost also provides the function set hash_value which already provides a hash function for std::pair, as well as std::tuple and most standard containers.

更准确地说, 。例如,每个对称对将哈希为0,并且仅通过置换而不同的对将具有相同的哈希。这可能对你的编程练习很好,但可能严重损害真实世界代码的性能。

More precisely, it will produce too many collisions. E.g., every symmetric pair will hash to 0 and pairs that differ only by permutation will have the same hash. This is probably fine for your programming exercise, but might seriously hurt performance of real world code.

这篇关于C ++ unordered_map具有pair作为键 - 不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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