map key_comp() function in C++ STL
Last Updated :
13 Jun, 2023
The map::key_comp() is a function in STL in C++ that returns a copy of comparison object used by container that compare keys.
Syntax:
map.key_comp()
Return value: This method returns the comparison object used by container that compare keys.
Below examples illustrate the working of key_comp() method:
Example:
CPP
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> mymap;
map<char, int>::key_compare
mycomp
= mymap.key_comp();
mymap['x'] = 50;
mymap['y'] = 100;
mymap['z'] = 150;
cout << "mymap contain:\n";
char highest = mymap.rbegin()->first;
map<char, int>::iterator
it
= mymap.begin();
do {
cout << it->first
<< " => " << it->second
<< "\n";
} while (mycomp((*it++).first, highest));
cout << "\n";
return 0;
}
|
Output:
mymap contain:
x => 50
y => 100
z => 150
Example 2:
CPP
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> mymap;
map<char, int>::key_compare
mycomp
= mymap.key_comp();
mymap['a'] = 100;
mymap['b'] = 200;
mymap['c'] = 300;
cout << "mymap contain:\n";
char highest = mymap.rbegin()->first;
map<char, int>::iterator
it
= mymap.begin();
do {
cout << it->first
<< " => "
<< it->second
<< '\n';
} while (mycomp((*it++).first, highest));
cout << '\n';
return 0;
}
|
Output:
mymap contain:
a => 100
b => 200
c => 300
Time complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...