map key_comp() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of map::key_comp() function in C++ STL.

What is Map in C++ STL?

Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.

What is map::key_comp()?

The map::key_comp( ) is a function which comes under <map> header file. This function returns a copy of a key comparison object. This is by default a less than object which works same like a less than operator <. The object checks the order of the element keys in the map container. This function takes the two arguments and checks its keys and returns true if the first element is smaller and should go before the second element, else will return false.

Syntax

Key_compare.key_comp();

Parameters

This function accepts no parameter.

Return value

It returns a comparison object.

Example

Input

map<char, int> newmap;
map<char, int> :: key_compare cmp = newmap.key_comp();
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;

Output

a = 1
b = 2
c = 3

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, char> TP;
   map<int, char>::key_compare cmp = TP.key_comp();
   // Inserting elements
   TP[0] = 'a';
   TP[1] = 'b';
   TP[2] = 'c';
   TP[3] = 'd';
   cout<<"Elements in the map are : \n";
   int val = TP.rbegin()->first;
   map<int, char>::iterator i = TP.begin();
   do {
      cout << i->first << " : " << i->second<<'\n';
   } while (cmp((*i++).first, val));
   return 0;
}

Output

Elements in the map are:
0 : a
1 : b
2 : c
3 : d

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<char, int> TP;
   map<char, int>::key_compare cmp = TP.key_comp();
   // Inserting elements
   TP['a'] = 0;
   TP['b'] = 1;
   TP['c'] = 3;
   TP['d'] = 2;
   cout<<"Elements in the map are : \n";
   char val = TP.rbegin()->first;
   map<char, int>::iterator i = TP.begin();
   do {
      cout << i->first << " : " << i->second<<'\n';
   } while (cmp((*i++).first, val));
   return 0;
}

Output

Elements in the map are:
a : 0
b : 1
c : 3
d : 2
raja
Published on 15-Apr-2020 12:12:15
Advertisements