如何在无序映射中为自定义类重用字符串类的哈希函数

How to reuse hashing function of string class for custom class in unordered map?

本文关键字:字符串 函数 哈希 自定义 无序 映射      更新时间:2023-10-16

我正在C++中定义一个无序映射,如下所示:

unordered_map<CustomClass, int, CustomClassHash, CustomClassEq> myMap;

假设我已经能够成功地定义CustomClassEq。我希望CustomClass的散列,即CustomClassHash委托给类内字符串属性的散列。有没有一种方法可以在CustomClassHash的定义中重用字符串类的哈希函数?

这就是我想做的:

struct CustomClassHash {
    long operator()(const CustomClass &c) const {
        string s = c.getString();
        // TODO: return the hash of s
    }
};

您可以使用: return hash<string>()(c.get_name());

查看后的第二条评论

对象作为无序映射的密钥