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

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

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


它应该是这样工作的:

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


我考虑过使用 vectortuple .

是否可以使用其中之一作为 unordered_map 的 key ?没有提前指定尺寸?


编辑:

我试过像这样使用@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;
 ^

最佳答案

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

关于C++ - 在 unordered_map 中使用多个值作为键的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32300593/

相关文章:

c++ - 更改xcode中特定代码字的颜色

c++ - C/C++调试原理/核心话题

c++ - 需要一个从 vector 派生的 vector

c++:如何将数据插入结构成员(位于 vector 中的结构)

c++ - 声明一个二维 vector

c++ - 我可以对 vector 进行排序以匹配 unordered_map 的排序吗?

c++ - 访问存储在 unordered_map 值中的 unordered_map

C++通过指针初始化char数组

c++ - 典型现代 CPU 的分支预测缓冲区有多大?

c++ - std::unordered_map 中的可能错误