0

I want to use a class as the key in a std::map.

std::map<Type, value> collection;

Although I defined operator<, the key isn't accepted: Invalid operands to binary expression ('const Type' and 'const Type').

class Type {
public:
    inline bool operator< (const Type& rhs) { /* ... */ }

Why is this happening?

Appleshell
  • 6,518
  • 4
  • 41
  • 91
  • 5
    Your member functions needs to be `const`: `inline bool operator< (const Type& rhs) const;` Even better, implement it as a non-member `friend` function for symmetry. – dyp May 02 '14 at 23:19

1 Answers1

6

You must define your operator< as

inline bool operator< (const Type& rhs) const { /* ... */ }

because map stores const key internally.


To expand a bit I'd also suggest (like dyp already did in the comments) That you use non-member operator overloads when possible. There are various advantages to them. I won't list them here since there already is good information on the advantages/differences, just let me link you to Operator overloading : member function vs. non-member function?.

Community
  • 1
  • 1
user1942027
  • 6,884
  • 6
  • 32
  • 44