C++ Standard Library C++ STL Library

C++ set - key_comp() Function



The C++ set::key_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

key_compare key_comp() const;
key_compare key_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::key_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 key_comp object
  set<int>::key_compare MyComp = MySet.key_comp();

  //printing all elements in set which are 
  //less than 50 using key_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