簡體   English   中英

如何具有unordered_multimaps的unordered_multimap

[英]How to have an unordered_multimap of unordered_multimaps

我正在通過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。

您的問題是沒有可用於CStringstd::hash專業化

將問題歸結為最簡單的部分,這也不會編譯:

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名稱空間中:

#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;    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM