C++ std::map key_comp() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::map

Definition

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
CallWhat 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

ParameterDescription
Nonekey_comp() takes no parameters. Call it with empty brackets.

Return Value

Return ValueDescription
key_compareA 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.

C++
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<int, std::string> m;
    auto comp = m.key_comp();

    std::cout << std::boolalpha;
    std::cout << "comp(1, 2): " << comp(1, 2) << '\n';
    std::cout << "comp(2, 1): " << comp(2, 1) << '\n';
    std::cout << "comp(5, 5): " << comp(5, 5) << '\n';
    return 0;
}

How It Works

  1. m.key_comp() returns the comparison object. The map has no pairs, but the comparison still exists, because it is part of the map type.
  2. The default is std::less<int>, so comp(1, 2) asks “is 1 < 2?” and the answer is true. comp(2, 1) is false.
  3. comp(5, 5) is false, because a key does not go before itself. This is the rule that makes keys unique.

Example 2 — key_comp() with std::greater

Create a map that sorts keys from big to small, and see the comparison change.

C++
#include <functional>
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<int, std::string, std::greater<int>> m = {{1, "one"}, {3, "three"}, {2, "two"}};

    std::cout << std::boolalpha;
    std::cout << "comp(1, 2): " << m.key_comp()(1, 2) << '\n';
    std::cout << "comp(2, 1): " << m.key_comp()(2, 1) << '\n';

    for (const auto& kv : m) {
        std::cout << kv.first << ' ';
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. The third template argument std::greater<int> tells the map to put bigger keys first.
  2. Now key_comp()(1, 2) asks “is 1 > 2?”, which is false. key_comp()(2, 1) asks “is 2 > 1?”, which is true.
  3. The comparison drives the order of the whole map, so the loop prints the keys 3 2 1.

Example 3 — key_comp() Defines When Keys Are Equal

Use a custom comparator that ignores letter case. Two spellings become the same key.

C++
#include <algorithm>
#include <cctype>
#include <iostream>
#include <map>
#include <string>

struct NoCase {
    bool operator()(const std::string& a, const std::string& b) const {
        return std::lexicographical_compare(
            a.begin(), a.end(), b.begin(), b.end(),
            [](unsigned char x, unsigned char y) { return std::tolower(x) < std::tolower(y); });
    }
};

int main() {
    std::map<std::string, int, NoCase> m;
    m["Apple"] = 1;
    m["APPLE"] = 2;

    auto comp = m.key_comp();
    bool equivalent = !comp("Apple", "APPLE") && !comp("APPLE", "Apple");

    std::cout << "size: " << m.size() << '\n';
    std::cout << m.begin()->first << "=" << m.begin()->second << '\n';
    std::cout << "equivalent: " << std::boolalpha << equivalent << '\n';
    return 0;
}

How It Works

  1. NoCase compares two strings letter by letter after lowering the case, so "Apple" and "APPLE" do not go before each other.
  2. 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.
  3. 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.

Next: lower_bound()

Keep going through the std::map functions. Find the first pair whose key is not less than the given key.

lower_bound() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful