Namespaces
Variants

std:: less

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
定义于头文件 <functional>
template < class T >
struct less ;
(C++14 前)
template < class T = void >
struct less ;
(C++14 起)

用于执行比较的函数对象。主模板在类型 T 上调用 operator <

目录

特化

实现 x < y 的函数对象,推导参数和返回类型
(类模板特化)

成员类型

类型 定义
result_type (C++17 中弃用) (C++20 中移除) bool
first_argument_type (C++17 中弃用) (C++20 中移除) T
second_argument_type (C++17 中弃用) (C++20 中移除) T

这些成员类型通过公开继承 std:: binary_function < T, T, bool > 获得。

(C++11 前)

成员函数

operator()
检查第一个参数是否 小于 第二个参数
(公开成员函数)

std::less:: operator()

bool operator ( ) ( const T & lhs, const T & rhs ) const ;
(constexpr since C++14)

检查 lhs 是否 小于 rhs

参数

lhs, rhs - 要比较的值

返回值

lhs < rhs

T 为指针类型,结果与 指针的实现定义严格全序 一致。

异常

可能抛出实现定义的异常。

可能的实现

constexpr bool operator()(const T& lhs, const T& rhs) const 
{
    return lhs < rhs; // assumes that the implementation handles pointer total order
}

示例

#include <functional>
template<typename A, typename B, typename C = std::less<>>
constexpr bool fun(A a, B b, C cmp = C{})
{
    return cmp(a, b);
}
static_assert(fun(1, 2) == true);
static_assert(fun(1.0, 1) == false);
static_assert(fun(1, 2.0) == true);
static_assert(std::less<int>{}(5, 5.6) == false);   // 5 < 5 (警告:隐式转换)
static_assert(std::less<double>{}(5, 5.6) == true); // 5.0 < 5.6
static_assert(std::less<int>{}(5.6, 5.7) == false); // 5 < 5 (警告:隐式转换)
static_assert(std::less{}(5, 5.6) == true);         // less<void>: 5.0 < 5.6
int main() {}

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 2562 C++98 指针全序可能不一致 保证一致性

参见

实现 x == y 的函数对象
(类模板)
实现 x > y 的函数对象
(类模板)
实现 x < y 的约束函数对象
(类)