Let’s say I have
struct Value { int foo(); };
size_t *begin = ...,
*end = ...;
If I want to sort a bunch of Value indices in C++03, I have to write something tedious like this:
struct Comparator
{
Value *data;
Comparator(Value *data) : data(data) { }
bool operator()(size_t a, size_t b)
{ return data[a].foo() < data[b].foo(); }
};
sort(begin, end, Comparator(data));
Is there any way to write this more neatly, preferably in 1 line, with Boost (perhaps with Boost.Lambda)?
Using Boost.Phoenix (which is the preferred lambda library of Boost):
An alternative is to use LocalFunction which essentially lets you do what you’re doing (passing a local type to
std::sort, which is not allowed for C++03) in a portable fashion. Usage should be (code is untested for this one though):