How do you write code in C++ to sort in descending order?

In C++, you can use the sort function from the Standard Template Library (STL) to achieve sorting in descending order.

Here is an example code:

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

// 比较函数,用于指定排序方式
bool compare(int a, int b) {
    return a > b; // 降序排序
}

int main() {
    std::vector<int> nums = {5, 2, 8, 3, 1};
  
    // 使用sort函数排序,并传入比较函数
    std::sort(nums.begin(), nums.end(), compare);

    // 输出排序结果
    for (int num : nums) {
        std::cout << num << " ";
    }

    return 0;
}

In the code above, we define a comparison function “compare” to sort the elements in descending order using the sort function. In the main function, we create a vector container called “nums” and input the numbers to be sorted into it. Then, we use the sort function to sort “nums”, passing the “compare” function as a parameter. Finally, we use a loop to output the sorted result.

The results will be: 8 5 3 2 1, they are arranged in descending order.

Leave a Reply 0

Your email address will not be published. Required fields are marked *