C++ multiset key_comp()C++ Multiset key_comp() function is used to return a copy of the comparison object which is used by the multiset container to compare keys. The comparison object can be used to compare key values of two elements in a container. This comparison object is given when constructing the object and it can be a pointer to a function or a function object. In either case, this takes two arguments of the same type, returning true if the first argument is before the second argument according to the narrower weak order, otherwise returns false. Note: By default, comparison object is a less object, which returns the same as operator <.SyntaxNote: A stored object defines member functions:ParameterNone Return valueIt returns a key comparison function object. ComplexityConstant. Iterator validityNo changes. Data RacesThe container is accessed. No contained elements are accessed: Concurrently accessing and modifying the elements is safe. Exception SafetyIf an exception is thrown, there are no changes in the container. Example 1Let's see the simple example to compare key values: Output: Compare keys (1 is true and 0 is false): 1 Compare keys (1 is true and 0 is false): 0 In the above example, comp(1, 5) returns true because 1 is less than 5 and comp(3, 2) returns false because 3 is not less than 2. Example 2Let's see a simple example: Output: mymultiset contains: 0 1 2 3 4 In the above example, highest variable stores the last element of the mymultiset multiset and iterator initialized with first element of the multiset (in sorted order). Do-while loop is used to print the element of the multiset where the loop will run until first key is less than last key (for this it is using key_comp() function named as mycomp). Example 3Let's see a simple example: Output: kc1( 2,3 ) returns value of true, where kc1 is the function object of s1. kc2( 2,3 ) returns value of false, where kc2 is the function object of s2. In the above example, there are two multisets used i.e. m1 and m2. The key comparison object of m1 is less and key comparison object of m2 is greater. Therefore, when we compare (2, 3) then kc1 function object of m1 returns true and kc2 function object of m2 returns false. Example 4Let's see a simple example: Output: use function object kc to find less of (10, 4)... kc(10, 4) == false, which means 10 > 4 In the above example, kc function object of multiset multisetobj compares (10, 4) if it is true, then it will return 10 < 4 and if it is not true, then it will return 10 > 4. Next TopicC++ multiset |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India