我对 hash_map 做了一些测试,使用 struct 作为键。我定义结构:
struct ST
{
bool operator<(const ST &rfs)
{
return this->sk < rfs.sk;
}
int sk;
};
和:
size_t hash_value(const ST& _Keyval)
{ // hash _Keyval to size_t value one-to-one
return ((size_t)_Keyval.sk ^ _HASH_SEED);
}
然后:
stdext::hash_map<ST, int> map;
ST st;
map.insert(std::make_pair<ST, int>(st, 3));
它给了我一个编译器错误:binary '<' : no operator found which takes a left-hand operand of type 'const ST' (or there are no acceptable conversion)
所以我将运营商改为非成员(member):
bool operator<(const ST& lfs, const ST& rfs)
{
return lfs.sk < rfs.sk;
}
没关系,所以我想知道为什么?
最佳答案
你错过了一个const
:
bool operator<(const ST &rfs) const
{
return this->sk < rfs.sk;
}
关于c++ - 为什么要将 operator< 定义为非成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16514505/