In this article we will discuss how to use User defined classes as key in std::map.

By default std::map uses “operator <” as sorting criteria for keys. For default data types like int and std::string etc, operator < is available by default but for User defined classes operator < is not available by default.

Therefore, to use user defined class objects as keys in std::map we should have either,

  • Default sorting criteria i.e. operator < defined for our Class.
  • std::map should be assigned with an external sorting criteria i.e. comparator that can compare two objects of your user defined class.

Lets understand by example,

Overloading operator < for sorting of keys

Suppose our class is User that has id and name properties. To use this class as key in std::map we will overload operator <.

Now create a std::map with Class User as key and an integer as value bonded with each key.
Here in above User class operator < compares the id of each user object. So, map will contain only user objects with unique keys.


Output :: Comparing by ID

Mr.X :: 100
Mr.Z :: 300
Mr.X :: 120

As we can see in output above, std::map can contain User object with unique Ids only therefore there are two entries for 2 Mr.X objects.

Now suppose we want to change the sorting criteria of keys i.e for User objects, instead of comparing by ID we want to compare them by name property.

To achieve this we have two options either change the definition of operator < or by using external sorting criteria i.e. comparators. For example,

Using Comparator for sorting of keys:


Output :: Comparing by NAME

Mr.Z :: 300
Mr.X :: 100

As we can see in above output there is only 1 entry for name Mr.X because this time because we are comparing keys i.e User objects by name instead of Id.

Complete executable code is as follows,



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.