dimanche 22 septembre 2019

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

There are resources out there for sorting an array in descending order:

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

How to sort C++ array in ASC and DESC mode?

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

but none address the question of doing this for a std::array and not primitive int myArr[] type.

I have a code like this:

#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;
    }

}

Which produces:

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

However, I am trying to produce this output:

100
30
22
6
0

By sorting the array in descending order. I have tried following the tips from the SO post above:

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

But that generates error:

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

How can I sort standard array of int in descending order?

Aucun commentaire:

Enregistrer un commentaire