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

Jer*_* M. 0 c++ arrays sorting c++11

有足够的资源可以按降序对数组进行排序:

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/

但没有人解决为a 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

产生:

30
22
100
6
0
NOW, SORTED:
0
6
22
30
100
Run Code Online (Sandbox Code Playgroud)

但是,我试图产生此输出:

100
30
22
6
0
Run Code Online (Sandbox Code Playgroud)

通过对数组进行降序排序。我尝试按照上面的SO帖子中的提示进行操作:

sort(myArray, myArray.size()+n, greater<int>());
Run Code Online (Sandbox Code Playgroud)

但这会产生错误:

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

我如何排序standard arrayint降序排列?

son*_*yao 6

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

sort(myArray.begin(), myArray.end(), greater<int>());
Run Code Online (Sandbox Code Playgroud)

要么

sort(std::begin(myArray), std::end(myArray), greater<int>());
Run Code Online (Sandbox Code Playgroud)

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

  • @JerryM。您需要了解什么是迭代器,以及如何获取要使用的容器类型的开始和结束迭代器。 (2认同)