Using sort () for top-down, not bottom-up C ++

I am trying to sort a user defined row or column of a 2d array. The code I have can be sorted 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 to downstream?

+3


source to share


4 answers


Use std::greater

as third parameterstd::sort

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

      



FYI .. when you use std::sort

without a third parameter, the third parameter is by default std::less

.

+5


source


You can use reverse iterators rbegin and rend, for example:

int main()
{
    int vec[6] {1,2,3,4,5,6};
    sort(rbegin(vec), rend(vec));

    for (const auto &i : vec) 
        cout << i << " ";
}

      

: 6 5 4 3 2 1

Or, you can 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 comparison function and pass it as the 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

+2


source


using sort (arr [index], arr [index] + 12, std :: greater ());

insted

sort( arr[index] , arr[index] + 12);

      

To sort in ascending order;

//Sorts the elements in the range [first,last) into ascending order.
std::sort(tempArr, tempArr + 12); // default sort

      

To sort in descending order

//you can use the comparator, the third argument in sort()
std::sort(tempArr, tempArr + 12, std::greater<int>());

      

see http://www.cplusplus.com/reference/algorithm/sort/

+1


source


sort

can only sort ascending ... but you can choose what ascending means.

If you sort

say that x

, y

is in ascending order if and only if, x > y

then the sorted sequence will be in ascending order operator >

, which is the same as in descending order operator <

.

You can write your own custom functor for this, or use a lambda, but the standard library already has a functor for this purpose:

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

      

In C ++ 14, you should use std::greater<>

instead std::greater<int>

.

0


source







All Articles