C++ Standard Library C++ STL Library

C++ map - value_comp() Function



The C++ map::value_comp function is used to compare two elements to get whether the key of the first one goes before the second.

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 map::value_comp function is used print all elements of the given map.

#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";

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

  //printing the content of the map using value_comp object
  it = MyMap.begin();
  cout<<"MyMap contains:\n ";
  do {
    cout<<it->first<<"  "<<it->second<<"\n ";
  } while(MyComp(*it++, *MyMap.rbegin()));

  return 0;
}

The output of the above code will be:

MyMap contains:
 101  John
 102  Marry
 103  Kim
 104  Jo
 105  Ramesh

❮ C++ <map> Library