C ++如何插入数组到unordered_map作为它的关键? [英] C++ How to insert array to unordered_map as its key?
本文介绍了C ++如何插入数组到unordered_map作为它的关键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi我以前有一个unordered_set来保存我的16 int数组,现在我需要再存储一个int作为它的桶。我不知道我是否可以将数组插入到我的unordered_set,或者我可以使用我以前使用的相同的模板?
#include < unordered_set>
#include< array>
namespace std
{
template< typename T,size_t N>
struct hash< array< T,N> >
{
typedef array< T,N> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a)const
{
hash< T>哈希尔
result_type h = 0;
for(result_type i = 0; i {
h = h * 31 + hasher(a [i]);
}
return h;
}
};
}
std :: unordered_set< std :: array< int,16> >闭锁
int main()
{
std :: array< int,16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
closelist.insert(sn);
}
我可以把它改成这个吗?
std :: unordered_map< std :: array< int,16>,int>闭锁
int main()
{
std :: array< int,16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
closelist.insert(sn,24);
}
我不明白模板,我不知道什么是h =谢谢!!!
解决方案
如何使用任何对象作为键:
- 将对象序列化为字节数组
- 计算加密散列(MD5或SHA)
- 将加密散列转换为指纹值(例如将其前64位转换为uint64_t)
- 使用此指纹作为地图键
缺点是您可能需要以某种方式解决冲突。
Hi I used to have a unordered_set to hold my 16 int array, now I need to store one more int as its bucket. I wonder if I can insert the array into my unordered_set, or can I use the same template I used to use?
#include <unordered_set>
#include <array>
namespace std
{
template<typename T, size_t N>
struct hash<array<T, N> >
{
typedef array<T, N> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a) const
{
hash<T> hasher;
result_type h = 0;
for (result_type i = 0; i < N; ++i)
{
h = h * 31 + hasher(a[i]);
}
return h;
}
};
}
std::unordered_set<std::array<int, 16> > closelist;
int main()
{
std::array<int, 16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
closelist.insert(sn);
}
Can I just change it to this?
std::unordered_map<std::array<int, 16>,int > closelist;
int main()
{
std::array<int, 16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
closelist.insert(sn,24);
}
And I couldn't understand the template, I wonder what is "h = h * 31 + hasher(a[i]);"?
Thank you!!!
解决方案
How to use any object as a key:
- Serialize the object into a byte array (for an array of ints just use the binary data as it is)
- Compute the cryptographic hash (MD5 or SHA)
- Convert the cryptographic hash into a fingerprint value (for example cast its first 64 bits into uint64_t)
- Use this fingerprint as a map key
The disadvantage is that you might need to resolve collisions somehow.
这篇关于C ++如何插入数组到unordered_map作为它的关键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文