C++ Standard Library C++ STL Library

C++ map - key_comp() Function



The C++ map::key_comp function returns a copy of the comparison object used by the container to compare keys. 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 map::key_comp function is used print all elements of the given map with key less than 104.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;
  map<int, string>::iterator it;

  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";
  MyMap[104] = "Jo";
  MyMap[105] = "Ramesh";

  //printing the content of the map
  cout<<"MyMap contains: \n ";
  for(it = MyMap.begin(); it != MyMap.end(); ++it)
     cout<<it->first<<"  "<<it->second<<"\n ";

  //creating a key_comp object
  map<int, string>::key_compare MyComp = MyMap.key_comp();

  //printing all elements of the map which has 
  //key than 104 using key_comp object
  it = MyMap.begin();
  cout<<"\nElements of MyMap with key less than 104:\n ";
  while(MyComp((*it).first, 104)){
    cout<<it->first<<"  "<<it->second<<"\n ";
    it++;
  }

  return 0;
}

The output of the above code will be:

MyMap contains: 
 101  John
 102  Marry
 103  Kim
 104  Jo
 105  Ramesh
 
Elements of MyMap with key less than 104:
 101  John
 102  Marry
 103  Kim

❮ C++ <map> Library