给定一个向量,请使用C++中的STL以降序对向量进行排序。
例子:
Input: vec = {1, 45, 54, 71, 76, 12}
Output: {76, 71, 54, 45, 12, 1}
Input: vec = {1, 7, 5, 4, 6, 12}
Output: {12, 7, 6, 5, 4, 1}
方法:可以借助STL中提供的sort()函数来完成排序。
句法:
sort(arr, arr + n, greater());
// C++ program to sort Vector
// in descending order
// using sort() in STL
#include
using namespace std;
int main()
{
// Get the vector
vector a = { 1, 45, 54, 71, 76, 12 };
// Print the vector
cout << "Vector: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
cout << endl;
// Sort the vector in descending order
sort(a.begin(), a.end(), greater());
// Print the reversed vector
cout << "Sorted Vector in descendiing order:n";
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 descendiing order:
76 71 54 45 12 1
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。