Hash function for user defined class. How to make friends? :)(用户定义类的哈希函数.如何结交朋友?:))
问题描述
我有一个 C 类,它有一个 string* ps 私有数据成员.
现在,我想要一个 unordered_map,我需要一个自定义哈希函数.
根据 c++ 参考,我可以这样做
命名空间标准{模板<>类哈希{上市:size_t operator()(const C &c) const{返回 std::hash()(*c.ps);}};} 问题是我似乎无法让 operator() 和 C 成为朋友,以便我可以访问 ps.>
我已经试过了:
C 类;模板<>类 std::hash<C>;C类{//...朋友 std::hash<C>::operator ()(const C&) const;//错误:类型不完整};//定义哈希这里. 但它说不完整的类型......在嵌套名称说明符......
我也无法扭转定义,因为如果稍后定义类 C,hash<C> 无法知道 ps.>
我在这里做错了什么?如何在不公开 ps 的情况下修复这种情况?
试试这个:
C 类;命名空间标准{模板<>结构散列<C>{上市:size_t operator()(const C &c) const;//还没有定义};}C类{//...朋友 size_t std::hash<C>::operator ()(const C&) const;};命名空间标准{模板<>size_t hash<C>::operator()(const C &c) const {返回 std::hash()(*c.ps);}} 或者这个:
C 类;模板<>struct std::hash<C>;C类{朋友结构 std::hash<C>;//为类添加友元,而不是成员函数};(我没有编译所以可能有语法错误)
I have a class C, which has a string* ps private data member.
Now, I'd like to have an unordered_map<C, int> for which I need a custom hash function.
According to the c++ reference, I can do that like
namespace std {
template<>
class hash<C> {
public:
size_t operator()(const C &c) const
{
return std::hash<std::string>()(*c.ps);
}
};
}
The problem is that I can't seem to make operator() and C friends so that I could access ps.
I have tried this:
class C;
template<>
class std::hash<C>;
class C{
//...
friend std::hash<C>::operator ()(const C&) const; // error: Incomplete type
};
// define hash<C> here.
but it says that Incomplete type ... in nested name specifier ...
I can't turn around the definitions either, because if class C is defined later, the hash<C> has no way to know about ps.
What am I doing wrong here? How can this situation be fixed without making ps public?
Try this:
class C;
namespace std {
template<>
struct hash<C> {
public:
size_t operator()(const C &c) const; // don't define yet
};
}
class C{
//...
friend size_t std::hash<C>::operator ()(const C&) const;
};
namespace std {
template<>
size_t hash<C>::operator()(const C &c) const {
return std::hash<std::string>()(*c.ps);
}
}
Or this:
class C;
template<>
struct std::hash<C>;
class C{
friend struct std::hash<C>; // friend the class, not the member function
};
(I haven't compiled so there might be a syntax error)
这篇关于用户定义类的哈希函数.如何结交朋友?:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用户定义类的哈希函数.如何结交朋友?:)
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
