Javatpoint Logo
Javatpoint Logo

C++ set value_comp()

C++ set value_comp() function returns a comparison object. This function is used to compare two elements to check whether the key of the first one goes before the second.

It takes two arguments of the same type and returns true if the first argument precedes the second argument according to the narrower weak order, and false otherwise.

E.g.: - For a set m, if two elements e1(k1, d1) and e2( k2, d2) are objects of type value_type, where k1 and k2 are their keys of type key_type and d1 and d2 are their data of type setped_type, then m value_comp( e1 , e2 ) is equivalent to m key_comp(k1, k2).


Note: A stored object defines a member function:

It returns true if the value of the left key precedes and does not equal the value of the key from right in the sort order.



Return value

It returns a value comparison function object.



Iterator validity

No changes.

Data Races

The container is accessed.

No contained elements are accessed: Concurrently accessing the elements of a set 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 values of elements:


Compare 2 to 5 (1 is true and 0 is false): 1
Compare 8 to 5 (1 is true and 0 is false): 0

In the above example, comp(2, 5) returns true because 2 is less than 5. And comp(8, 5) returns false because 8 is not less than 5.

Example 2

Let's see a simple example:


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:


vc1( 2,3 ) returns value of true, where vc1 is the function object of s1.
vc2( 2,3 ) returns value of false, where vc2 is the function object of s2.

Example 4

Let's see a simple example to show the difference between key_comp() and value_comp():


highest1 is 5
highest2 is 5

In the above example, when we compare key_comp() and value_comp() then for such set containers these two words are the same. For both type of functions it will return the same value.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA