C++ C++;如何将数组作为键插入无序的_映射?

C++ C++;如何将数组作为键插入无序的_映射?,c++,c++11,unordered-map,C++,C++11,Unordered Map,嗨,我以前有一个无序的_集合来保存我的16 int数组,现在我需要再存储一个int作为它的存储桶。我想知道是否可以将数组插入无序的集合,或者是否可以使用以前使用的模板 #include <unordered_set> #include <array> namespace std { template<typename T, size_t N> struct hash<array<T, N> > {

嗨,我以前有一个无序的_集合来保存我的16 int数组,现在我需要再存储一个int作为它的存储桶。我想知道是否可以将数组插入无序的集合,或者是否可以使用以前使用的模板

#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);
}
#包括
#包括
名称空间标准
{
模板
结构散列
{
typedef数组参数_类型;
类型定义大小\u t结果\u类型;
结果类型运算符()(常量参数类型&a)常量
{
散列哈希器;
结果_型h=0;
对于(结果类型i=0;i
我能换成这个吗

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);
    }
std::无序地图关闭列表;
int main()
{
数组sn={1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15};
关闭列表。插入(序号24);
}
我无法理解模板,我想知道什么是“h=h*31+hasher(a[I]);”

谢谢你

我能换成这个吗

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);
    }
首先,您的阵列初始化错误:

std::array<int, 16> sn = {{1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15}};
//                        ^                                     ^
因此,您应该传递
std::pair
(或可转换为
std::pair
)的内容,例如:

closelist.insert({sn,24});
或者更简单一点:

closelist[sn] = 24;

如何将任何对象用作键:

  • 将对象序列化为字节数组(对于int数组,只需按原样使用二进制数据)
  • 计算加密散列(MD5或SHA)
  • 将加密散列转换为指纹值(例如,将其前64位转换为uint64\t)
  • 将此指纹用作地图密钥

  • 缺点是您可能需要以某种方式解决冲突。

    “我想知道什么是
    h=h*31+hasher(a[I]);
    ”-在这一行中,您只需计算数组的哈希值。你到底不明白什么?@很快什么是31?我问了这个问题,有个好人给了我这个模板…
    31
    只是一个常量。这取决于对数组中元素的限制。除非确实需要,否则通常不使用任何加密哈希。加密散列在计算上更加密集。此外,找到一个完美的散列函数(应用程序不存在冲突)始终是一个挑战。在大多数情况下,标准实现工作得非常好。