【问题标题】:C++ unordered_map user defined typeC++ unordered_map 用户定义类型
【发布时间】:2010-11-18 03:22:28
【问题描述】:

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

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

报错信息如下:

In function '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': 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 reference to 'std::hash<DateTime>::operator()(DateTime) const'

谢谢。

【问题讨论】:

  • 您的问题严重缺乏代码、准确且完整的错误消息,以及有关您正在使用的编译器的信息。
  • 我认为这是stackoverflow.com/questions/647967/…的副本
  • 如果有人知道如何在反引号内转义反引号,请随意(我在编辑中将它们更改为 ')。这些行太长,“缩进 4 个空格”无法使用。根据错误信息,编译器是某种 GCC。

标签: c++ stl


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复。我的 datetime 结构具有我认为可以用作哈希键的刻度值。有没有方法可以让我将 unordered_map 设置为直接使用刻度值作为哈希键?
  • @Steven:如果它是公共数据成员,您可以使用 boost::mem_fun(&amp;DateTime::ticks) 获得所需的散列函子,但我害怕认为您必须将类型设置为第二个模板std::unordered_map 的参数。编写专业化可能更容易。
  • @Steven:在上面安德烈的代码中,你有没有试过安德烈说要放/* [your] hash algorithm */...的“v.ticks”?
  • @Steven 是的,试试 Tony 说的
猜你喜欢
  • 1970-01-01
  • 2013-06-05
相关资源
最近更新 更多