Can we use a user defined class for the key in a STL map?

Any type can be used as a key as long as it is

  • Copyable
  • Assignable
  • Comparable, since the map is sorted by key

If your class is just a simple structure, then it’s already copyable and assignable. For a class to be comparable, you must either implement operator<, or create the map with a custom comparison function to use instead.

The only impact on time efficiency comes from larger objects taking longer to copy and compare. If the objects need to be that size, then there’s nothing you can do about that, so don’t worry about it.

Leave a Comment