Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: key_comp

From cppreference.net

key_compare key_comp ( ) const ;
(自 C++26 起为 constexpr)

返回用于比较键的函数对象,该对象是 * this 所使用的键比较对象的副本。

目录

返回值

关键比较函数对象。

复杂度

常量。

示例

#include <iostream>
#include <map>
#include <utility>
// 示例模块97键比较函数
struct ModCmp
{
    bool operator()(int lhs, int rhs) const
    {
        return (lhs % 97) < (rhs % 97);
    }
};
int main()
{
    std::map<int, char, ModCmp> cont;
    cont = {{1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'}, {5, 'e'}};
    auto comp_func = cont.key_comp();
    for (const auto it : cont)
    {
        const bool before = comp_func(it.first, 100);
        const bool after = comp_func(100, it.first);
        std::cout << "键 (" << it.first << ',' << it.second << ") ";
        if (!before && !after)
            std::cout << "等价于键 (100)\n";
        else if (before)
            std::cout << "位于键 (100) 之前\n";
        else if (after)
            std::cout << "位于键 (100) 之后\n";
        else
            std::unreachable();
    }
}

输出:

(1,a) 位于键 (100) 之前
(2,b) 位于键 (100) 之前
(3,c) 等价于键 (100)
(4,d) 位于键 (100) 之后
(5,e) 位于键 (100) 之后

参见

返回用于比较 value_type 类型对象中键的函数
(公开成员函数)