c++boostc++03boost-lambda

How to use Boost (Lambda?) to make std::sort() easier?


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


Solution

  • Using Boost.Phoenix (which is the preferred lambda library of Boost):

    #include <boost/phoenix/phoenix.hpp>
    
    {
        // for bind and ref
        using namespace boost::phoenix;
    
        using namespace boost::phoenix::placeholders;
        std::sort(begin, end
                  , bind(&Value::foo, ref(data)[arg1]) < bind(&Value::foo, ref(data)[arg2]) );
    }
    

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

    #include <boost/local_function.hpp>
    
    {
        int BOOST_LOCAL_FUNCTION(const bind& data, std::size_t lhs, std::size_t rhs)
        {
            return data[lhs].foo() < data[rhs].foo();
        } BOOST_LOCAL_FUNCTION_NAME(comparator)
    
        std::sort(begin, end, comparator);
    }