我不明白为什么我不能使用 unordered_map
和 array<int,3>
作为密钥类型:
#include <unordered_map>
using namespace std;
int main() {
array<int,3> key = {0,1,2};
unordered_map< array<int,3> , int > test;
test[key] = 2;
return 0;
}
我得到一个很长的错误,最相关的部分是
main.cpp:11:9: error: no match for ‘operator[]’ (operand types are std::unordered_map<std::array<int, 3ul>, int>’ and ‘std::array<int, 3ul>’)
test[key] = 2;
^
数组是否因为缺少某些要求而没有资格成为键?
原文由 Adrien 发布,翻译遵循 CC BY-SA 4.0 许可协议
为什么?
如 http://www.cplusplus.com/reference/unordered_map/unordered_map/ 中所述
现在根据您的问题,我们需要
hash
一个尚未在标准 C++ 内部实现的数组。如何克服它?
因此,如果您想将
array
映射到一个值,您必须实现自己的 std::hash http://en.cppreference.com/w/cpp/utility/hash ,您可能会得到一些帮助从 C++ 如何将数组插入哈希集中? .一些解决方法
如果您可以自由使用
boost
那么它可以为您提供数组和许多其他类型的散列。它基本上使用hash_combine
方法,您可以查看 http://www.boost.org/doc/libs/1_49_0/boost/functional/hash/hash.hpp 。