One-line rsort of an integer array

Posted on: 03/10/2009

Suppose you have an array of integers and a comparator function object. We would like to have the array sorted in a reverse order.. Using only one 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::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.


1 Response to "One-line rsort of an integer array"

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);


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

The most elegant 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: