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:
// C++ program to demonstrate map::key_comp(). #include <iostream> #include <map> using namespace std; int main() { // Declare the map map<char, int> mymap; // Compare the key. map<char, int>::key_compare mycomp = mymap.key_comp(); // Populate the map mymap['x'] = 50; mymap['y'] = 100; mymap['z'] = 150; // Print the map cout << "mymap contain:\n"; char highest = mymap.rbegin()->first; // key value of last element map<char, int>::iterator it = mymap.begin(); do { cout << it->first << " => " << it->second << "\n"; } while (mycomp((*it++).first, highest)); cout << "\n"; return 0; } |
mymap contain: x => 50 y => 100 z => 150
Example 2:
// C++ program to demonstrate map::key_comp(). #include <iostream> #include <map> using namespace std; int main() { // Declare the map map<char, int> mymap; // Compare the key. 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; // key value of last element map<char, int>::iterator it = mymap.begin(); do { cout << it->first << " => " << it->second << '\n'; } while (mycomp((*it++).first, highest)); cout << '\n'; return 0; } |
mymap contain: a => 100 b => 200 c => 300
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- map::at() and map::swap() in C++ STL
- Searching in a map using std::map functions in C++
- How to copy a map to another map in Golang?
- map cbegin() and cend() function in C++ STL
- map crbegin() and crend() function in C++ STL
- map upper_bound() function in C++ STL
- map lower_bound() function in C++ STL
- map find() function in C++ STL
- map erase() function in C++ STL
- map emplace_hint() function in C++ STL
- map count() function in C++ STL
- map rbegin() function in C++ STL
- map rend() function in C++ STL
- map rbegin() function in C++ STL
- Descending order in Map and Multimap of C++ STL
- Map in C++ Standard Template Library (STL)
- Map of pairs in STL
- Traversing a map (or unordered_map) in C++ STL
- map::clear() in C++ STL
- map::size() in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

