All queries about std::map having key as custom class object | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

All queries about std::map having key as custom class object

Hi Once we use to have map for custom class , we need to have < operator defined... It is because third default argument for the map is less function object and hence we need to have this defined. If we have custom comparator , < is not must... What is priority by compiler if both are defined and have different implementation? Another question is need of < operator... I belive that it is required when we insert element... Does it require for deletion or find operation as well ? Find means comparision to check equal to or not... Then how it works without asking us to have overloaded == operator for custom class ?

9th Mar 2022, 7:57 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 1
Last part ans... std::map does not care about literal unicity of the keys. It cares about keys equivalence. The keys a and b are equivalent by definition when neither a < b nor b < a is true. Simply operator < is enough. Equality can be checked by testing a < b and b < a both returning false. Original ans is https://stackoverflow.com/questions/20168173/when-using-stdmap-should-i-overload-operator-for-the-key-type#:~:text=You%20should%20overload%20operator%3C%20.,as%20a%20test%20for%20uniqueness.
9th Mar 2022, 12:58 PM
saurabh
saurabh - avatar
0
Thanks for your help ROOKIE
9th Mar 2022, 4:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Regarding my first question about choice between custom comparator and <, it is never the case. Refer code below: https://code.sololearn.com/c6WexWpRFRa3 If we provide third argument into map declaration as comparator function, compiler choses the same . Other wise < is chosen and it is must to be defined.
9th Mar 2022, 4:07 PM
Ketan Lalcheta
Ketan Lalcheta - avatar