One-line rsort of an integer array

October 3rd, 2009 § 1 Comment

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.

Tagged: , ,

§ One Response to One-line rsort of an integer array

  • NN says:

    You can use Boost.Lambda:

    #include <boost/lambda/lambda.hpp>
    std::sort(arr, arr +n, _2 < _1);

    :)

    BTW, why use old arrays ?

    boost::array<int, 3> arr = ....
    
    sort(reverse_iterator(arr.begin()), reverse_iterator(arr.end()), comp);

    [2]

    sort(arr.begin(), arr.end(), _2 < _1);

    The most elegant :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading One-line rsort of an integer array at 0x.

meta