C++ - 在 unordered_map 中使用多个值作为键的最佳方式

C++ - Optimal way to use multiple values as a key in unordered_map

我正在编写 class 以处理状态空间。我的问题是,我不知道在 unordered_map.

中使用多个值作为键的理想方法是什么

它应该这样工作:

我创建了值为 <1;0;8> 的状态对象,因此它将作为 <1;0;8>:pointer_to_object 插入到哈希图中。我想要哈希图,因为我需要找到 对象尽可能快。


我考虑过使用 vector or tuple

是否可以使用其中之一作为 unordered_map 的键而不预先指定它们的大小?


编辑:

我试过像这样使用@the_mandrill推荐的代码:

template <class T>
typedef std::unordered_map<std::vector<T>, State<T>*, boost::hash<std::vector<T>> Map;

template <class T>
size_t hash_value(const std::vector<T>& vec)
{
    std::size_t seed = 0;
    for (const auto& val : vec) {
      boost::hash_combine(seed, val);
    }
    return seed;
}

但是我收到这个错误:

stateSpaceLib.cpp:79:83: error: template argument 3 is invalid
 typedef std::unordered_map<std::vector<T>, State<T>*, boost::hash<std::vector<T>> Map;
                                                                                   ^
stateSpaceLib.cpp:79:1: error: template declaration of ‘typedef’
 typedef std::unordered_map<std::vector<T>, State<T>*, boost::hash<std::vector<T>> Map;
 ^

大小是 tuple 类型的一部分,因此它不起作用。

vector 并非如此,因此使用它作为密钥应该可以正常工作。

不幸的是,std:hash 没有接受 vector<int> 的标准重载;您也许可以使用 boost 来弥补这一点 (http://en.cppreference.com/w/cpp/utility/hash)。或者,您可以提供自己的哈希函数。

您应该能够使用矢量 - 可以单独使用,也可以将其包装在包含您需要的任何其他状态数据的结构中,然后如果您可以访问 boost,则使用 hash_combine:

typedef std::unordered_map<std::vector<int>, ObjectPointer, boost::hash<std::vector<int>> Map;

size_t hash_value(const std::vector<int>& vec)
{
    std::size_t seed = 0;
    for (const auto& val : vec) {
      boost::hash_combine(seed, val);
    }
    return seed;
 }