map key_comp() in C++ STL
Last Updated :
24 Oct, 2018
The std::map::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container.By default, this is a less object, which returns the same as operator ‘<'.It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise.Two keys are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
Syntax:
key_compare map_name.key_comp();
Parameters: This function does not accept any parameter.
Return value: The function returns a copy of the comparison object used by the container.
Below examples illustrate map::key_comp() method:
Program 1:
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< char , int > m;
map< char , int >::key_compare
comp
= m.key_comp();
m[ 'a' ] = 10;
m[ 'b' ] = 20;
m[ 'c' ] = 30;
m[ 'd' ] = 40;
cout << "Map has the elements\n" ;
char l = m.rbegin()->first;
map< char , int >::iterator it = m.begin();
do {
cout << it->first
<< " => "
<< it->second
<< '\n' ;
} while (comp((*it++).first, l));
return 0;
}
|
Output:
Map has the elements
a => 10
b => 20
c => 30
d => 40
Program 2:
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< char , int > m;
map< char , int >::key_compare
comp
= m.key_comp();
m[ 'a' ] = 1;
m[ 'b' ] = 2;
m[ 'c' ] = 3;
m[ 'd' ] = 4;
cout << "Map has the elements\n" ;
char l = m.rbegin()->first;
map< char , int >::iterator it = m.begin();
do {
cout << it->first
<< " => "
<< it->second
<< '\n' ;
} while (comp((*it++).first, l));
return 0;
}
|
Output:
Map has the elements
a => 1
b => 2
c => 3
d => 4
Share your thoughts in the comments
Please Login to comment...