0

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

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

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。

4

1 回答 1

2

您的问题是没有std::hash可用的专业化CString

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

std::unordered_multimap<CString , int> m_Map2;    

因为std::unordered_multimap<CString, anything>需要存在一个std::hash<CString>提供的类std::size_t operator()(CString const&) const(它还需要一个实现,std::equal_to<CString>但如果CString支持operator==.

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

#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;    
于 2019-08-21T11:16:30.163 回答