set value_comp() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we are going to discuss the set::value_comp() in C++ STL, their syntax, working and their return values.

What is Set in C++ STL?

Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.

What is set::value_comp()?

value_comp() is an inbuilt function in C++ STL which is declared in <set> header file. value_comp() returns a copy of the comparison object, which is used by the set container for the comparisons. By default, this object is less than the operator’s object. It is a type of function pointer or a function object which do the comparison of the two values of the same type in a particular set and returns true if the first element is smaller than the second element in the container, else it returns false. In set containers the values are the keys themselves so they are placed in the set container in the sorted format, so the function value_comp() and key_comp() works in a similar manner.

Syntax

comparison_object set_name.value_comp();

Parameter

This function accepts no parameters.

Return value

This function returns a comparison object of the associated set container.

Example

Input: set <int> myset = {9, 8, 7, 6, 5};
   set<int>::value_compare cmp = myset.value_comp()
Output: 5 6 7 8 9

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> Set;
   set<int>::value_compare cmp = Set.value_comp();
   for (int i = 0; i <= 10; i++)
      Set.insert(i);
   cout<<"elements in set are: ";
   int front = *Set.rbegin();
   set<int>::iterator i = Set.begin();
   do {
      std::cout << *i << " ";
   }
   while (cmp(*(++i), front));
   std::cout << '\n';
   return 0;
}

Output

If we run the above code it will generate the following output −

elements in set are : 0 1 2 3 4 5 6 7 8 9
raja
Published on 05-Mar-2020 10:38:58
Advertisements