While overloading the operator< for custom key in map, why is const required for both the argument and the function type?
The value_type for an std::map<K, V> is not std::pair<K, V> as you might think, but actually std::pair<const K, V>. Therefore, any comparison invoked on the keys deals with const objects.
Now when the compiler sees
a < b
and at least one of a or b is of user-defined type, the compiler calls either
operator < (a, b); //(1)
or
a.operator < (b); //(2)
(if both of these are available, an error is issued).
A non-constant member-function, including any operator, can only be invoked on non-constant objects. So, because a is constant, it is required that in case of //2 the function be declared const. Since b is constant too, the parameter must be a const reference, because non-const references cannot be bound to constant objects. Hence the requirement for both consts.
The parameter has another option apart from being const. It could take the parameter by value, but that would mean unnecessary copying. Similarly, if you chose to declare a non-member operator <, you should take both parameters either by const reference (recommended) or by value.
The prototype for the operator< is
bool operator<(const Element& b) const { ..... }
const Element& b means that extra copies of the element b are not created upon invocation of the operator< as well as the arguments are not modified inside the method. The second const means that the object on which the operator< is called will not be modified upon this call invocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With