在unordered_map中使用多个值作为键的最佳方法
C++ - Optimal way to use multiple values as a key in unordered_map
我正在编写用于处理状态空间的类。我的问题是,我不知道,在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)。或者,您可以提供自己的哈希函数。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 转换/映射方法最佳做法