📜  C++中的std :: greater_equal与示例(1)

📅  最后修改于: 2023-12-03 14:59:50.698000             🧑  作者: Mango

C++中的std::greater_equal与示例

std::greater_equal是C++标准库中的函数对象类型,用于比较两个值是否大于或等于。它是C++中的一个内联模板函数,可以用于任何比较支持小于或等于运算符的类型。

语法
template <typename T> struct greater_equal {
    bool operator()(const T& x, const T& y) const;
};
示例

下面是一个示例,展示如何使用std::greater_equal比较两个整数是否相等:

#include <iostream>
#include <functional>

int main() {
    std::greater_equal<int> greater_eq;
    
    int a = 5;
    int b = 3;
    
    if (greater_eq(a, b)) {
        std::cout << "a is greater than or equal to b" << std::endl;
    } else {
        std::cout << "a is less than b" << std::endl;
    }
    
    return 0;
}

输出结果:

a is greater than or equal to b

在该示例中,我们首先创建一个std::greater_equal<int>,然后使用该函数对象比较两个整数ab。由于a大于b,因此返回true,最终输出结果为a is greater than or equal to b

总结

std::greater_equal是C++标准库中用于比较两个值是否大于或等于的函数对象类型。它非常适合用于标准库算法,例如std::sortstd::find_if等,也可以用于自定义类对象的比较。熟练掌握这一函数对象类型可以帮助我们更加方便和高效地编写C++程序。