简体   繁体   中英

how does custom comparator works exactly

Given std::map< int, int, std::greater<int> > m;

By default items that are inserted to maps are sorted in ascending order. With the above definition I understand that we can change the sort order to descending.

I want to know how exactly custom comparator works. For example, when will this argument be checked, or where exactly in map implementation is this argument utilized?

The map associates keys with values . So, it consist of key /value pairs. In order to insert an new pair in the map or find an existing one, the program must be able to compare the key from the request with the key s which exist in the map. For this reason the comparators are used. The stl provides you with a few standard comparators, like less , greater , less_equals , greater_equal . They provide a common interface for 'map' to use and do < , > , <= , >= operation on the pairs of key s. So, during the 'map' operations the comparator's operator() is called with 2 keys to compare them.

The default comparator is 'less'. So, in your case the comparator will return true if the first int key is less than the second int key . This would guarantee a particular order of insertion of the pairs in the map. If you explicitly use the 'greater' comparator, it will return 'false' in the case above and it will change the order in which elements are inserted.

You can also think about a sorted list or an array where the every previous element is less than the second. if you change your comarator for sorting to be greater the sorted array will be reversed.

You can create a custom comparator as well and do some different types of compare operations.

In general a custom comparator might be needed for simple types, like int, char *, ... If you use an object as a 'key' element, you can just overload the operator< , if the less comparator is in use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM