在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
热门推荐
10 新年祝福语大全 简短情侣
11 对转校同学祝福语简短
12 迎元旦平安祝福语简短
13 康复儿童六一祝福语简短
14 元旦祝福语 简短独特群发
15 冬日问候祝福语大全简短
16 医美的祝福语大全简短
17 开盘大吉的简短祝福语
18 伴娘祝福语简短朋友的话