C++如何将数组插入unordered_map作为其键?

wee*_*eeo 6 c++ unordered-map c++11

嗨我曾经有一个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> 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);
}
Run Code Online (Sandbox Code Playgroud)

我可以改成它吗?

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);
    }
Run Code Online (Sandbox Code Playgroud)

我无法理解模板,我想知道什么是"h = h*31 + hasher(a [i]);"?

谢谢!!!

awe*_*oon 1

我可以把它改成这样吗?

首先,你的数组初始化是错误的:

std::array<int, 16> sn = {{1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15}};
//                        ^                                     ^
Run Code Online (Sandbox Code Playgroud)

由于std::array没有带std::initializer_list参数的构造函数。因此,第一级用于初始化对象,第二级用于初始化对象中的数组。

其次,从参考

std::pair<iterator,bool> insert( const value_type& value );

template <class P> 
std::pair<iterator,bool> insert( P&& value );
Run Code Online (Sandbox Code Playgroud)

所以,你应该传递std::pair(或其他东西,可转换为std::pair),例如:

closelist.insert({sn,24});
Run Code Online (Sandbox Code Playgroud)

或者,更简单:

closelist[sn] = 24;
Run Code Online (Sandbox Code Playgroud)