如何按降序对标准数组进行排序 - C++ 11.

How to sort a standard array in descending order - C++ 11

本文关键字:排序 C++ 数组 何按 降序 标准      更新时间:2023-10-16

有一些资源可以按降序对数组进行排序:

https://www.includehelp.com/stl/sort-an-array-in-descending-order-using-sort-function.aspx

如何在ASC和DESC模式下对数组进行排序C++?

https://www.geeksforgeeks.org/sort-c-stl/

但是没有一个解决为std::array而不是基int myArr[]类型执行此操作的问题。

我有这样的代码:

#include <iostream>
#include <array>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
int main(){
array<int, 5> myArray = {30, 22, 100, 6, 0};
for(int item : myArray){
cout << item << endl;
}
sort(myArray.begin(), myArray.end());
cout << "NOW, SORTED: " << endl;
for (int otheritem: myArray){
cout << otheritem << endl;
}
}

它产生:

30
22
100
6
0
NOW, SORTED:
0
6
22
30
100

但是,我正在尝试生成此输出:

100
30
22
6
0

通过按降序对数组进行排序。我已经尝试遵循上面SO帖子中的提示:

sort(myArray, myArray.size()+n, greater<int>());

但这会产生错误:

no instance of overloaded function "sort" matches the argument list -- argument types are: (std::array<int, 5ULL>, unsigned long long, std::greater<int>)

如何按降序对intstandard array进行排序?

与原始数组不同,std::array不会隐式转换为指针(即使你可以从std::array::data中显式获取指针(,你应该使用begin()end(),它们通常用于从 STL 容器中获取迭代器。

例如
sort(myArray.begin(), myArray.end(), greater<int>());

sort(std::begin(myArray), std::end(myArray), greater<int>());

PS:后者也适用于原始数组。