c++ - 如何在键是自定义对象的情况下使用 stdext::hash_map?

标签 c++ stl hashmap

使用 STL C++ hash_map...

class MyKeyObject
{
    std::string str1;
    std::string str2;

    bool operator==(...) { this.str1 == that.str1 ... }
};

class MyData
{
    std::string data1;
    int data2;
    std::string etcetc;
};

像这样...

MyKeyObject a = MyKeyObject(...);
MyData b = MyData(...);

stdext::hash_map <MyKeyObject, MyData> _myDataHashMap;
_myDataHashMap[ a ] = b;

我收到一大堆错误。这是前三个...

Error 1 error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const MyKeyObject' c:\program files\microsoft visual studio 8\vc\include\functional 143

Error 2 error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const Tasking::MyKeyObject' c:\program files\microsoft visual studio 8\vc\include\functional 143

Error 3 error C2784: 'bool std::operator <(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'const MyDataObject' c:\program files\microsoft visual studio 8\vc\include\functional 143

...

如果我将 key 设置为像 int 这样简单的东西,一切都很好。

我做错了什么?!也许我需要用模板做点什么?

有没有更好(更快?)的方法来使用像这样的自定义键对象访问数据?

最佳答案

要使用哈希表,您需要指定一个哈希函数。您需要创建一个函数对象,它代表一个接受 MyKeyObject 的函数。对象并返回 size_t .然后将仿函数作为初始大小之后的第二个参数传递:

hash_map <MyKeyObject, MyData> _myDataHashMap(initial_size, YourHashFunctor());

或者,您可以将哈希函数编写为 hash<T> 的模板特化你的类型的仿函数;这样您就不需要传入自定义哈希函数。

我不知道您为什么会特别收到这些错误。也许它试图将您的对象用作哈希码或其他东西?在任何情况下,如果没有哈希函数,它都不应该工作。哈希函数是为整数类型和字符串预定义的。

关于c++ - 如何在键是自定义对象的情况下使用 stdext::hash_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1059545/

相关文章:

c++ - 有没有一种方法可以处理鼠标移动并执行 MessageBeep?

c++ - 如何在大型 C++ 程序中为所有 double 类型的数字设置小数精度

C++ STL 堆栈问题 : Why does pop() not throw an exception if the stack is empty?

c++ - 将容器中的每个元素划分为给定数字 C++

c++ - 确定一个元素是否被插入到 HashMap 中

C++类继承

C++/CX - 我需要从 const char* 实例化 Platform::String

c++ - 如何在 C++ 中定义具有四个值的优先级队列?

java - "put"会覆盖现有值吗?

java - 如何将KStream的Object类型的值存储在Hashmap中?