+ 1

map of map with custom class

Refer code below: https://www.sololearn.com/en/compiler-playground/c4K0LmgGspgf If we want to have custom class as a key to map, it need < operator to be overloaded for a class. What to be done when we need map as key to outer map like map<map<test,test>,int> to work.

20th Jan 2025, 4:04 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Respostas
21st Jan 2025, 3:13 AM
Bob_Li
Bob_Li - avatar
0
For map of key as custom class object, we need to override < operator. This operator helps our map container to decide which object is smaller than other. Same way, refer code below: https://www.sololearn.com/en/compiler-playground/chQ97wZb9Zxc Here, mp1 and mp2 both are same due to same value and hence mp size is 1. try changing either key or value from either mp1 or mp2 and will have size of mp as 2. So, I am curious like what is code doing so that it compares two map<map<test,test>,int>? For map<test,int> , it uses < from class test. so, for map<map<test,test>,int>, should not it be using something from map class?
21st Jan 2025, 8:54 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
stl maps defaults to comparing keys. since you have overloaded the operator< in your custom class, it can work out a default sorting order. equal keys are overwritten. https://sololearn.com/compiler-playground/cMFK79NYx6kV/?ref=app
21st Jan 2025, 9:44 AM
Bob_Li
Bob_Li - avatar