.key_comp
Anonymous contributor
Published Jun 14, 2025
Contribute to Docs
The .key_comp()
function returns a copy of the comparison function object (typically key_compare
) used by the container to order its keys.
Syntax
myMap.key_comp();
Parameters:
.key_comp()
takes no parameters.
Return value:
- Returns the key comparison function object used by the map to order its keys.
- By default, this is
std::less<Key>
unless a custom comparator was specified when defining the map.
- By default, this is
Example
This is an example demonstrating how to use .key_comp()
to compare keys in a std::map
:
#include <iostream>#include <map>int main() {std::map<int, std::string> myMap = {{1, "Apple"},{2, "Banana"},{3, "Orange"},{4, "Date"},{5, "Mango"}};auto comp = myMap.key_comp();int keyToCompare = 3;for (const auto& pair : myMap) {if (comp(pair.first, keyToCompare)) {std::cout << pair.first << " is less than " << keyToCompare << std::endl;} else if (comp(keyToCompare, pair.first)) {std::cout << pair.first << " is greater than " << keyToCompare << std::endl;} else {std::cout << pair.first << " is equal to " << keyToCompare << std::endl;}}return 0;}
The output of this code will be:
1 is less than 32 is less than 33 is equal to 34 is greater than 35 is greater than 3
Codebyte Example
This is a codebyte example demonstrating how to use .key_comp()
to compare keys in a std::map
:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.