C ++ unordered_map用户定义类型

C ++ unordered_map用户定义类型

问题描述:

我有一个类用作unordered_map中的键。当我试图编译代码时,它显示未定义的引用 std :: hash< typeName> :: operator()(typename)const 。我怎么能去修复它?什么额外的函数需要重载,使用户定义的类型在unordered_map中使用?

I am having a class which is used as the key in the unordered_map. When I tried to compiled the code, it shows undefined reference to std::hash<typeName>::operator()(typename) const. How could I go to fix it? What additional function do I need to overload to make the user defined type to be used in an unordered_map?

我有一个dateTime结构存储日期和时间的信息。

I have a dateTime struct which stores the info of date and time.

错误消息如下:

在函数'std :: __ detail :: _ Hash_code_base< DateTime,std :: pair< DateTime const,int>,std :: _Select1st< std :: pair< DateTime const,int> >,std :: equal_to< DateTime&gt ;, std :: hash< DateTime&gt ;, std :: __ detail :: _mod_range_hashing,std :: __ detail :: _ Default_ranged_hash,false> :: _ M_hash_code(DateTime const& $ b testing.cpp :( .text._ZNKSt8__detail15_Hash_code_baseI10DateTimeSt4pairIKS1_DeESt10_Select1stIS4_ESt8equal_toIS1_ESt4hashIS1_ENS_18_Mod_range_hashingENS_20_Default_ranged_hashELb0EE12_M_hash_codeERS3_ [std :: __ detail :: _ Hash_code_base< DateTime,std :: pair< DateTime const,int> std :: _ Select1st< std :: pair< DateTime const,int> ,std :: equal_to< DateTime&gt ;, std :: hash< DateTime&gt ;, std :: __ detail :: _mod_range_hashing,std :: __ detail :: _ Default_ranged_hash,false> :: _ M_hash_code(DateTime const&)const] + 0x23):undefined引用'std :: hash< DateTime> :: operator()(DateTime)const'

$ b

你必须实现哈希算法,否则标准容器不会选择你的类型,因为它不知道如何计算哈希码。 p>

you have to implement hash algorithm, otherwise standard container will not pick your type, because it has no idea how to calculate hash code for it.

namespace std
{    
   template <>
   struct hash<DateTime> : public unary_function<DateTime, size_t>
   {
       size_t operator()(const DateTime& v) const
       {
           return /* my hash algorithm */;
       }
   };
}