扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c++中sort降序排序怎么实现

扬州沐宇科技
2024-04-18 10:36:06
c++

在C++中,可以使用std::sort函数和自定义的比较函数来实现降序排序。以下是一个示例代码:

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

bool compare(int a, int b) {
    return a > b; // 降序排序
}

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

    std::sort(vec.begin(), vec.end(), compare);

    for (int i : vec) {
        std::cout << i << " ";
    }

    return 0;
}

在上面的代码中,定义了一个名为compare的比较函数,该函数返回a > b,表示降序排序。然后在std::sort函数中传入这个比较函数,在对vec进行排序时就会按照降序的方式进行。

扫码添加客服微信