In C++, std::map::key_comp() returns a copy of the comparison object that the map uses to put its keys in order. You call that object like a function with two keys, and it says whether the first key comes before the second.
The default comparison is std::less<Key>, which gives ascending order. You can choose another one, such as std::greater, when you create the map. Include <map> to use it.
This is a member of std::map<Key, T>, a sorted container of key and value pairs. Each key is unique and the pairs are always kept in key order, so a map can find, insert, and erase a key in logarithmic time. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Call key_comp to get the comparison object, then call that object with two keys.
C++
auto comp = m.key_comp();
bool before = comp(1, 2); // true for std::less
bool same = m.key_comp()(5, 5); // false
Call
What it does
m.key_comp()
Returns the key_compare object of the map.
m.key_comp()(a, b)
Calls the comparison on two keys. Returns true if a goes before b in the map.
Two keys a and b are treated as equal by the map when neither goes before the other: !comp(a, b) && !comp(b, a). The map never uses == on keys.
Library declarations
C++
key_compare key_comp() const;
Parameters
Parameter
Description
None
key_comp() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
key_compare
A copy of the comparison object used to order the keys. Usually std::less<Key>.
C++ Examples
Example 1 — key_comp() Compares Keys
Get the comparison object of a default map and call it on two keys.
NoCase compares two strings letter by letter after lowering the case, so "Apple" and "APPLE" do not go before each other.
m["APPLE"] = 2 finds the existing key "Apple" because the map sees them as equal. It only overwrites the value, so the size stays 1 and the stored key keeps its first spelling.
key_comp() returns a NoCase object. If comp(a, b) and comp(b, a) are both false, the keys are equivalent, which prints true.
Frequently Asked Questions
A copy of the comparison object the map uses to order its keys. By default it is std::less<Key>.
Give the map std::greater as its third template argument: std::map<int, std::string, std::greater<int>>. key_comp() then returns that comparison.
It treats keys a and b as equal when neither comp(a, b) nor comp(b, a) is true. It does not use operator==.
key_comp() compares two keys. value_comp() compares two whole pairs, but it only looks at their keys.
No. The comparison is part of the map type and is fixed when the map is created.