2

In my program it program the array prints from ascending order, but i'm trying to modify it so it prints in descending order. Could use some help.

#include <iostream>
#include <algorithm>
int main()
{
    const int length = 5;
    int array[length] = {35, 67, 75, 60, 11};

    std::sort(std::begin(array), std::end(array));
    for(int i = 0; i < length; i++)
    {
      std::cout << array[i] << ' ';
    }

    return 0;
}
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • 2
    look at this https://stackoverflow.com/questions/9025084/sorting-a-vector-in-descending-order – samini Sep 02 '19 at 06:34

3 Answers3

5

std::sort can take 3rd parameter, a comparator, which will say how to order the elements inside the array. You can pass one of standard comparators inside your call to std::sort

std::sort(std::begin(array), std::end(array), std::greater<int>{});
Kaldrr
  • 2,780
  • 8
  • 11
0
std::reverse(std::begin(array), std::end(array));

Another solution using lambda expression

std::sort(std::begin(arr),std::end(arr),[](int a, int b) {
    return b < a; 
});

Output:

75 67 60 35 11
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
0

Another alternative is to go all in on iterators. You already know std::begin. Now it is time to meet its mirror-universe double: std::rbegin

for(auto it = std::rbegin(array); it != std::rend(array); ++it)
{
  std::cout << *it << ' ';
}

Documentation for rbegin

Documentation for rend

user4581301
  • 33,082
  • 7
  • 33
  • 54