In this article we will discuss how to use external sorting criteria for keys in std::map and points that we need to take care with external sorting criteria.

Default sorting criteria for keys in std::map is operator “<” i.e. std::less<T>. So, while creating std::map if we don’t specify the external sorting criteria then default criteria will be used.
For example,

will output the elements in lexicographical order.

Output:

earth :: 1
moon :: 2
sun :: 3

But suppose we want that elements in map to be stored in reverse lexicographical order of keys, then how to do it?
Obviously we cannot change the definition of opeartor < for std::string. Then in such scenario we should use external sorting criteria i.e. a function object opposite that behaves opposite to default operator <.

External sorting criteria i.e. Comparator,

std::map with external sorting criteria i.e. Comparator

Output:

sun :: 3
moon :: 2
earth :: 1

Comparing std::map objects with different external key sorting criteria

We can compare two std::map objects using operator ==, < , > etc but with same type of key sorting criteria only.

 

For example,

In  below two std::map objects, sorting criteria for keys is of different types and hence comparison of these std::map objects will result in compile time error.

For Comparison of two std::map objects only type of sorting criteria of keys should be same, it doesn’t matter of they are using the same object of that or not.

For example,

If Our Sorting Criteria is,

Then there will be no compile error for below code because here type of sorting criteria is same i.e.WordComparator for both the std::map objects even if both are using different objects of WordComparator .

Complete executable code is as follows,

 

Click Here to Subscribe for more Articles / Tutorials like this.