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.
You can use Boost.Lambda:
BTW, why use old arrays ?
[2]
The most elegant