Reputation: 192
I do some test on hash_map, using struct as key. I define struct:
struct ST
{
bool operator<(const ST &rfs)
{
return this->sk < rfs.sk;
}
int sk;
};
and:
size_t hash_value(const ST& _Keyval)
{ // hash _Keyval to size_t value one-to-one
return ((size_t)_Keyval.sk ^ _HASH_SEED);
}
then:
stdext::hash_map<ST, int> map;
ST st;
map.insert(std::make_pair<ST, int>(st, 3));
It gives me a compiler error:binary '<' : no operator found which takes a left-hand operand of type 'const ST' (or there is no acceptable conversion)
So I change the operator to non-member:
bool operator<(const ST& lfs, const ST& rfs)
{
return lfs.sk < rfs.sk;
}
It's OK.So I want to know why?
Upvotes: 0
Views: 96
Reputation: 9749
Despite of above answers, I recommend you have a look at:
C++ Primer, Fourth Edition, Chapter 14, section 14.1
Ordinarily we define the arithmetic and relational operators as nonmember functions and we define assignment operators as members:
Upvotes: 0
Reputation: 40036
I believe the problem is
error:binary '<' : no operator found which takes a left-hand operand of type 'const ST' (or there is no acceptable conversion)
Your member function bool operator<(const ST &rfs)
is declared non-const, so that it cannot be invoked against a const ST.
Just change it to bool operator<(const ST &rfs) const
and it should work
Upvotes: 0
Reputation: 52365
You were missing a const
:
bool operator<(const ST &rfs) const
{
return this->sk < rfs.sk;
}
Upvotes: 4