📜  C ++中的std :: greater以及示例(1)

📅  最后修改于: 2023-12-03 15:13:45.634000             🧑  作者: Mango

C++中的std::greater以及示例

1. std::greater简介

std::greater是C++标准库中的函数对象,定义在头文件<functional>中。它用于比较两个值的大小关系,返回类型为bool类型,表示左侧操作数是否大于右侧操作数。与std::less相反,std::greater实现了“大于”比较运算符。

template <typename T>
struct greater {
  bool operator()(const T& x, const T& y) const {
    return x > y;
  }
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};
2. std::greater示例

下面我们来看一个std::greater的使用示例。

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

int main()
{
    std::vector<int> vec = { 3, 1, 4, 1, 5, 9 };

    // sort using the default operator<
    std::sort(vec.begin(), vec.end());
    for (const auto& i : vec) {
        std::cout << i << ' ';
    }
    std::cout << '\n';

    // sort using a standard library compare function object
    std::sort(vec.begin(), vec.end(), std::greater<int>());
    for (const auto& i : vec) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
}

输出结果为:

1 1 3 4 5 9 
9 5 4 3 1 1

我们可以通过传递std::greater作为std::sort的第三个参数来使排序变成降序排列。

除了std::sort函数,我们还可以在其他涉及到比较大小的函数中使用std::greater,例如:

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

int main()
{
    std::vector<int> vec = { 3, 1, 4, 1, 5, 9 };

    // find the smallest odd number
    auto it = std::find_if(vec.begin(), vec.end(), std::bind(std::modulus<int>(), std::placeholders::_1, 2));
    if (it != vec.end()) {
        std::cout << "The smallest odd number is " << *it << '\n';
    }

    // count the number of elements greater than or equal to 4
    int count = std::count_if(vec.begin(), vec.end(), std::bind(std::greater_equal<int>(), std::placeholders::_1, 4));
    std::cout << "The number of elements greater than or equal to 4 is " << count << '\n';
}

上述代码中,我们在std::find_ifstd::count_if函数中使用了std::bind来绑定std::modulusstd::greater_equal的两个参数,并将操作数绑定到std::placeholders::_1上。

3. 总结

本文介绍了C++标准库中的std::greater函数对象的基本用法和示例。std::greater用于比较两个值的大小关系,实现了“大于”比较运算符。在实际开发中,我们可以在需要比较大小的场景中使用std::greater,提高代码可读性,减少编写重复代码的数量。