I am trying to sort the user given row or column of a 2d array. The code I have can sort in ascending order but not descending.
void sortArray(int arr[12][12], int index, int row)
{
   if (row == 0)
   {
       sort( arr[index] , arr[index] + 12);
   }
   else 
   {
       int tempArr[12];
       getColArr(arr, tempArr, index);
       sort(tempArr, tempArr + 12);
       for (int i = 0; i < 12; i++)
       {
           arr[i][0] = tempArr[i];
       }
   }
}
How do I change it into descending?
Use std::greater as third parameter of std::sort
std::sort(begin(vec), end(vec),std::greater<int>());
FYI..when you use std::sort without third parameter, third parameter is defaulted with std::less.
You can use reverse iterators rbegin and rend, example:
int main()
{
    int vec[6] {1,2,3,4,5,6};
    sort(rbegin(vec), rend(vec));
    for (const auto &i : vec) 
        cout << i << " ";
}
output: 6 5 4 3 2 1
Or you may use a lambda as the third argument to sort:
int vec[6] = {1,2,3,4,5,6};
sort(vec, vec+6, [](int i, int j){return i>j;});
If you don't have a compiler that supports C++11 or C++14, you can create your own compare function and pass it as third argument to sort:
bool isGreater(int i, int j)
{
    return i > j;
}
int main()
{
    int vec[6] = {1,2,3,4,5,6};
    sort(vec, vec+6, isGreater);
    for (int i = 0; i != 6; ++i)
        cout << vec[i] << " ";
}
Output: 6 5 4 3 2 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With