C++ set key_comp()
C++ set key_comp() function is used to return a copy of the comparison object which is used by the set 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 <.
Syntax
Note: A stored object defines member functions:
Returns true if _Left precedes and is not equal to _Right in the sort order.
Parameter
None
Return value
It returns a key comparison function object.
Complexity
Constant.
Iterator validity
No changes.
Data Races
The container is accessed.
No contained elements are accessed: Concurrently accessing and modifying the elements is safe.
Exception Safety
If an exception is thrown, there are no changes in the container.
Example 1
Let’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 2
Let’s see a simple example:
Output:
myset contains: 0 1 2 3 4
In the above example, highest variable stores the last element of the myset set and iterator initialized with first element of the set (in sorted order). Do-while loop is used to print the element of the set 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 3
Let’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 sets 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 4
Let’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 set setobj 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.