首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何拥有unordered_multimaps的unordered_multimap

如何拥有unordered_multimaps的unordered_multimap
EN

Stack Overflow用户
提问于 2019-08-21 18:45:31
回答 1查看 201关注 0票数 0

我在通过unordered_multimaps练习时遇到了一个问题,一个包含另一个unordered_multimap编译器的unordered_multimap.The抛出了一个错误,说c++标准不提供这种类型的散列。我想我必须写一个散列函数,但我的理解是有限的,因为我是新手。

我已经尝试过将结构或另一个多映射插入到unordered_multimap中,但到目前为止还没有成功。

代码语言:javascript
复制
std::unordered_multimap<long,long>m_Map1;
std::unordered_multimap<CString,m_Map1>m_Map2;    //This line throws 
error
//inserting to the map
m_Map1.insert(std::pair<long,long>(10,20));
m_Map2.insert(_T("ABC"),m_Map1);
//also the compiler does not let me create an object for this map
m_Map1 m_ObjMap;    //error here as well

我想要实现的是一个人的姓名与出生日期和死亡日期相关联。我希望将日期放在一个映射中,并将其与姓名映射到m_Map2。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-21 19:16:30

您的问题是没有可用于CStringstd::hash专门化

将问题简化为最简单的部分,也不会编译:

代码语言:javascript
复制
std::unordered_multimap<CString , int> m_Map2;    

因为std::unordered_multimap<CString, anything>要求存在一个提供std::size_t operator()(CString const&) const的类std::hash<CString> (它还需要一个std::equal_to<CString>实现,但是如果CString支持operator==,这个实现将自动可用。

您可以创建这样一个类,并将其合法地注入到std命名空间中:

代码语言:javascript
复制
#include <unordered_map>
#include <boost/functional/hash.hpp>  // for boost::hash_range, see below

// for exposition
struct CString
{
    const char* data() const;
    std::size_t length() const;

    bool operator==(CString const& other) const;
};

namespace std
{
    // specialise std::hash for type ::CString
    template<> struct hash<::CString>
    {
        std::size_t operator()(CString const& arg) const
        {
            std::size_t seed = 0;

            // perform whatever is your hashing function on arg here
            // accumulating the hash into the variable seed
            // in this case, we're doing it in terms of boost::hash_range

            auto first = arg.data();
            auto last = first + arg.length();
            boost::hash_range(seed, first, last);

            return seed;
        }
    };
}

std::unordered_multimap<CString , int> m_Map2;    
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57589909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档