温馨提示×

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

c++
小亿
121
2024-04-18 10:36:06
栏目: 编程语言

在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进行排序时就会按照降序的方式进行。

0