繁体   English   中英

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

[英]C++ How to insert array to unordered_map as its key?

嗨,我曾经有一个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);
}

我可以将其更改为此吗?

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);
    }

而且我听不懂模板,不知道什么是“ h = h * 31 + hasher(a [i]);”?

谢谢!!!

我可以将其更改为此吗?

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

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

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

其次,从参考

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

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

closelist.insert({sn,24});

或者,更简单:

closelist[sn] = 24;

如何将任何对象用作键:

  1. 将对象序列化为字节数组(对于整数数组,请按原样使用二进制数据)
  2. 计算加密哈希(MD5或SHA)
  3. 将密码哈希转换为指纹值(例如,将其前64位转换为uint64_t)
  4. 将此指纹用作地图密钥

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM