How to use sort() in C++ with custom sort member function?

It is, but in general I would encourage just using a proper functor or a lambda:

Using a lambda:

std::sort(payloadIndices.begin(), payloadIndices.end(), [this](int a, int b){
    return this->sortByWeights(a, b);
});

Alternatively using std::mem_fn:

auto sorter = std::bind(std::mem_fn(SimpleGreedyMappingTechnique::sortByWeights), this);
std::sort(payloadIndices.begin(), payloadIndices.end(), sorter);

Alternatively using a functor:

namespace{
struct indicies_less_than
{
    const SimpleGreedyMappingTechnique & mapping_tech;
    indicies_less_than(const SimpleGreedyMappingTechnique & mapping_tech)
       :mapping_tech(mapping_tech){}

    bool operator()(int a, int b)
    {
       return mapping_tech.sortByWeights(a, b);
    }
};
}

std::sort(payloadIndices.begin(), payloadIndices.end(), indicies_less_than(*this));

Note:

if the types being sorted were anything more complicated than an int you would definitely want to pass them by const& to prevent copying

Leave a Comment