Posted by: rmn 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::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.
06/12/2009 at 15:14
You can use Boost.Lambda:
#include
std::sort(arr, arr +n, _2 < _1);
BTW, why use old arrays ?
boost::array x = ….
sort(reverse_iterator(arr.begin()), reverse_iterator(arr.end()), comp)
[2]
sort(arr.begin(), arr.end(), _2 < _1);
The most elegant