One-line rsort of an integer array

Suppose you have an array of integers and a comparator function object. Your mission, should you choose to accept it, is to sort the array in a reversed order.. Using only a single line of code.

Find below a few ways to achieve just that using the STL and Boost libraries. More suggestions are most welcome.

#include <algorithm>
#include <functional>
#include <iostream>
#include <boost/bind.hpp>

struct Comparator : public std::binary_function<int, int, bool> {
    bool operator() (int l, int r) const {
        return l<r; // just an example
    }
};

int main () {
    int arr[] = { 13, 17, 20, 3, 16, 7, 19, 56 };
    const int n = sizeof(arr) / sizeof(arr[0]);
    Comparator comp;

    // [1] simplest solution, creating reverse iterators:
    std::sort(std::reverse_iterator<int*>(arr+n),
            std::reverse_iterator<int*>(arr), comp);
    // [2] gotta love Boost's bind to reverse comparison:
    std::sort(arr, arr+n, boost::bind<bool>(comp, _2, _1));
    // [3] may be incorrect, since (!(a<x)) = (a>=x) != (a>x):
    std::sort(arr, arr+n, std::not2(comp));
    // [4] arguably a one-liner, but still:
    std::sort(arr, arr+n, comp), std::reverse(arr, arr+n);

    // to print array's contents:
    std::copy(arr, arr+n,
            std::ostream_iterator<int>(std::cout, " "));

    return 0;
}

Can you think of more one-liners? Consider this a challenge.

One thought on “One-line rsort of an integer array

  1. You can use Boost.Lambda:

    #include &lt;boost/lambda/lambda.hpp&gt;
    std::sort(arr, arr +n, _2 &lt; _1);

    🙂

    BTW, why use old arrays ?

    boost::array&lt;int, 3&gt; arr = ....
    
    sort(reverse_iterator(arr.begin()), reverse_iterator(arr.end()), comp);

    [2]

    sort(arr.begin(), arr.end(), _2 &lt; _1);

    The most elegant 🙂

Leave a Reply