In C++, std::set::key_comp() returns a copy of the comparison object that the set uses to put its values in order. You call that object like a function with two values, and it says whether the first value comes before the second.
On a set the “key” is the value itself. The default comparison is std::less<T>, which gives ascending order. You can choose another one, such as std::greater, when you create the set. Include <set> to use it.
This is a member of std::set<T>, a sorted container of unique values. A set never keeps a duplicate and always holds its values in sorted order, so it can find, insert, and erase a value in logarithmic time. A set has no operator[] and no at(), because the value is its own key. Every element is const, so you cannot change a value through an iterator.
Syntax
Call key_comp to get the comparison object, then call that object with two values.
C++
auto comp = s.key_comp();
bool before = comp(1, 2); // true for std::less
bool same = s.key_comp()(5, 5); // false
Call
What it does
s.key_comp()
Returns the key_compare object of the set.
s.key_comp()(a, b)
Calls the comparison on two values. Returns true if a goes before b in the set.
Two values a and b are treated as equal by the set when neither goes before the other: !comp(a, b) && !comp(b, a). The set never uses == on values.
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 values. Usually std::less<T>.
C++ Examples
Example 1 — key_comp() Compares Values
Get the comparison object of a default set and call it on two values.
NoCase compares two strings letter by letter after lowering the case, so "Apple" and "APPLE" do not go before each other.
The second insert("APPLE") finds the existing value because the set sees them as equal. Nothing new is stored, so the size stays 1 and the first spelling remains.
key_comp() returns a NoCase object. If comp(a, b) and comp(b, a) are both false, the values are equivalent, which prints true.
Frequently Asked Questions
A copy of the comparison object the set uses to order its values. By default it is std::less<T>.
Give the set std::greater as its second template argument: std::set<int, std::greater<int>>. key_comp() then returns that comparison.
It treats values a and b as equal when neither comp(a, b) nor comp(b, a) is true. It does not use operator==.
On a set they compare the same element type. key_comp() takes two keys (the values). value_comp() takes two value_type elements, which for a set are also the values.
No. The comparison is part of the set type and is fixed when the set is created.