【问题标题】:C++ - Optimal way to use multiple values as a key in unordered_mapC++ - 在 unordered_map 中使用多个值作为键的最佳方式
【发布时间】:2015-08-30 20:01:11
【问题描述】:

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


它应该这样工作:

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


我考虑过使用vectortuple

是否可以将其中一个用作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 的用途。但我不明白你最后一段是什么意思。
  • @AlanStokes 我已经重写了,希望现在更好一点。
  • Re: 语法错误 - 你需要一个额外的 '>': boost::hash&lt;std::vector&lt;T&gt;&gt;&gt;

标签: c++ vector unordered-map stdtuple state-space


【解决方案1】:

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

【讨论】:

  • 是否可以参数化数据类型?我的意思是template &lt;class T&gt;
  • @Eenoku:是的 - 只要尝试一下,如果遇到问题,请提出具体问题。
  • 好的,ObjectPointer 是什么?我把它当作一个未声明的符号。
  • @TonyD 我已将我的第一次尝试添加到描述中。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 2021-11-12
    • 2014-10-18
    • 1970-01-01
    • 2017-05-27
    • 2011-06-09
    相关资源
    最近更新 更多