Dan*_*ode 6 c++ operators unordered-set c++11
什么是
operator size_t () const
Run Code Online (Sandbox Code Playgroud)
环境:Visual Studio 2010 Professional
TL; DR
今天我正在寻找一种使用方法std::tr1::unordered_set.因为我上次询问如何使用std::map,我决定自己找出来.
我用Google搜索,大部分结果告诉我有一个结构来进行散列.这种方式对我来说有点复杂,我一直在寻找并最终遇到了另一种方法.
我需要实施
bool operator == (const edge & another) const
Run Code Online (Sandbox Code Playgroud)
和
operator size_t () const
Run Code Online (Sandbox Code Playgroud)
结果代码接近问题的结尾.
==熟悉没有任何问题.size_t也很熟悉.但是什么operator size_t呢?
好像equals和hashCode对Java,它需要根据有效的Java被覆盖起来.但我不确定,尤其是名字的时候size_t.
结果代码如下.完整的程序工作正常,并产生正确的输出.
class edge {
public:
int x;
int y;
edge(int _x, int _y) : x(_x), y(_y) {
}
bool operator == (const edge & another) const {
return (x == another.x && y == another.y);
}
operator size_t () const {
return x * 31 + y;
}
};
Run Code Online (Sandbox Code Playgroud)
多一点点:
不
size_t operator () const
Run Code Online (Sandbox Code Playgroud)
无法编译:
error C2143: syntax error : missing ';' before 'const'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2059: syntax error : '{'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body
Run Code Online (Sandbox Code Playgroud)
即便没有
int operator size_t () const
Run Code Online (Sandbox Code Playgroud)
但正如我所看到的,该函数返回int.错误代码如下:
error C2549: user-defined conversion cannot specify a return type
Run Code Online (Sandbox Code Playgroud)
Pra*_*ian 14
它是类型转换操作符.在这种情况下,基本上提供隐式转换对象到指定类型size_t.
编辑:
假设您有一个定义如下的函数:
void Foo( size_t x )
{
// do something with x
}
Run Code Online (Sandbox Code Playgroud)
如果您的类edge定义了转换为的类型转换运算符,则size_t可以执行以下操作:
edge e;
Foo( e );
Run Code Online (Sandbox Code Playgroud)
编译器会自动将edge对象转换为size_t.正如@litb在评论部分所说,不要这样做.隐式转换可能会导致编译器在您可能没有意图实现转换时执行转换.
你应该改为定义一个成员函数edge::to_size_t()(我知道这是一个可怕的名字)来执行转换.
例如,std::string定义std::string::c_str()成员函数,而不是定义转换为的类型转换运算符const char *.
编辑2:
对不起,我没有仔细阅读你的问题.现在我看到你正试图在课堂上使用你的课程std::unordered_set.在这种情况下,您应该定义执行散列的仿函数并比较类的操作.或者,您可以为类提供模板特化std::hash,std::equal_to也不必在创建unordered_set对象时指定可选模板参数.
正如您在问题中提到的那样,这非常类似于Java的hashCode()成员函数,但由于C++类并非都源自像Java类这样的公共基类,因此它不是作为可覆盖的基类函数实现的.