在C ++中以降序对向量排序
可以使用std::sort()在C++中对向量进行排序。它在<algorithm>标头中定义。为了获得稳定的排序,使用了std::stable_sort。完全一样,sort()但保持相等元素的相对顺序。Quicksort(),mergesort()也可以根据要求使用。
可以使用std::greater<>()对向量进行降序排序。
算法
Begin
Declare v of vector type.
Initialize some values into v in array pattern.
Print “Elements before sorting”.
for (const auto &i: v)
print all the values of variable i.
Print “Elements after sorting”.
Call sort(v.begin(), v.end(), greater <>()) function to sort all the
elements in descending order of v vector.
for (const auto &i: v)
print all the values of variable i.
End.这是在C++中对向量进行排序的简单示例:
示例
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 };
cout<<"Elements before sorting"<<endl;
for (const auto &i: v)
cout << i << ' '<<endl;
cout<<"Elements after sorting"<<endl;
sort(v.begin(), v.end(), greater <>());
for (const auto &i: v)
cout << i << ' '<<endl;
return 0;
}输出结果
Elements before sorting 10 9 8 6 7 2 5 1 Elements after sorting 10 9 8 7 6 5 2 1