我在通过unordered_multimaps练习时遇到了一个问题,一个包含另一个unordered_multimap编译器的unordered_multimap.The抛出了一个错误,说c++标准不提供这种类型的散列。我想我必须写一个散列函数,但我的理解是有限的,因为我是新手。
我已经尝试过将结构或另一个多映射插入到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。
发布于 2019-08-21 19:16:30
您的问题是没有可用于CString的std::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; https://stackoverflow.com/questions/57589909
复制相似问题