简体   繁体   English

自定义比较器是如何工作的

[英]how does custom comparator works exactly

Given std::map< int, int, std::greater<int> > m;鉴于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 .map相关联。 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.为了插入地图中的一个新的一对或发现一个现有的,该程序必须能够比较来自与存在于地图中的密钥s的请求的密钥 For this reason the comparators are used.为此,使用比较器。 The stl provides you with a few standard comparators, like less , greater , less_equals , greater_equal . stl 为您提供了一些标准比较器,例如lessgreaterless_equalsgreater_equal They provide a common interface for 'map' to use and do < , > , <= , >= operation on the pairs of key s.它们为 'map' 提供了一个通用接口,以便在对上使用和执行<><=>=操作。 So, during the 'map' operations the comparator's operator() is called with 2 keys to compare them.因此,在“映射”操作期间,比较器的operator()将使用 2 个键调用以进行比较。

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 .因此,在您的情况下,如果第一个int key小于第二个int key ,则比较器将返回 true 。 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.如果您明确使用 'greater' 比较器,则在上述情况下它将返回 'false',并且会更改元素插入的顺序。

You can also think about a sorted list or an array where the every previous element is less than the second.您还可以考虑排序列表或数组,其中每个前一个元素都less第二个元素。 if you change your comarator for sorting to be greater the sorted array will be reversed.如果您将用于排序的 comarator 更改为greater则排序的数组将被反转。

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.一般而言,可能需要自定义比较简单的类型,如int,字符*,......如果你使用一个对象作为“钥匙”元素,你可以重载operator< ,如果less比较正在使用中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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