c++ - Why should operator< be defined as non-member? -


i test on hash_map, using struct key. 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 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 compiler error:binary '<' : no operator found takes left-hand operand of type 'const st' (or there no acceptable conversion)

so change operator non-member:

bool operator<(const st& lfs, const st& rfs) {     return lfs.sk < rfs.sk; } 

it's ok.so want know why?

you missing const:

bool operator<(const st &rfs) const {     return this->sk < rfs.sk; } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -