C ++ unordered_map用户定义类型 [英] C++ unordered_map user defined type

查看:203
本文介绍了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> ;, std :: hash< DateTime> ;, 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> ;, std :: hash< DateTime> ;, 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 */;
       }
   };
}

这篇关于C ++ unordered_map用户定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆