在unordered_map中使用多个值作为键的最佳方法

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

本文关键字:方法 最佳 unordered map      更新时间:2023-10-16

我正在编写用于处理状态空间的类。我的问题是,我不知道,在unordered_map中使用多个值作为键的理想方法是什么。


应该是这样工作的:

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


我考虑过使用vector或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;
 ^

您应该能够单独使用矢量,或者将其与您需要的任何其他状态数据包装在一个结构中,然后如果您可以访问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;
 }

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

但这不是vector的情况,所以使用它作为键应该工作得很好。

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