C ++ unordered_map,以对为键 - 不编译 [英] C++ unordered_map with pair as key - not compiling

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

问题描述

我正在尝试创建一个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> > >'

如果我使用常规地图,如$ code,我没有收到此错误> map< pair< string,string>,int> 而不是unordered_map。

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,以对为键 - 不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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