如何在 C++ 中使用 STL 对向量进行降序排序?
c++server side programmingprogramming
在本教程中,我们将讨论一个程序,以了解如何在 C++ 中使用 STL 对向量进行降序排序。
为了对给定的向量进行降序排序,我们将使用 C++ 中 STL 库中的 sort() 函数。
示例
#include <bits/stdc++.h> using namespace std; int main(){ //收集向量 vector<int> a = { 1, 45, 54, 71, 76, 12 }; cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; //按降序排序 sort(a.begin(), a.end(), greater<int>()); cout << "Sorted Vector in descending order: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; return 0; }
输出
Vector: 1 45 54 71 76 12 Sorted Vector in descending order: 76 71 54 45 12 1