C++ set - value_comp() Function
The C++ set::value_comp function returns a copy of the comparison object used by the container. By default, it is a less object, which returns the same as operator<.
Syntax
value_compare value_comp() const;
value_compare value_comp() const;
Parameters
No parameter is required.
Return Value
The comparison object associated to the container.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the set::value_comp function is used print all elements in the given set which are less than 50.
#include <iostream> #include <set> using namespace std; int main (){ set<int> MySet{10, 20, 30, 40, 50, 60, 70, 80, 90}; set<int>::iterator it; //printing the content of the set cout<<"MySet contains:"; for(it = MySet.begin(); it != MySet.end(); ++it) cout<<" "<<*it; //creating a value_comp object set<int>::value_compare MyComp = MySet.value_comp(); //printing all elements in set which are //less than 50 using value_comp object it = MySet.begin(); cout<<"\n\nElements less than 50 in MySet:\n"; while(MyComp(*it, 50)){ cout<<*it<<" "; it++; } return 0; }
The output of the above code will be:
MySet contains: 10 20 30 40 50 60 70 80 90 Elements less than 50 in MySet: 10 20 30 40
❮ C++ <set> Library