Humam Helfawi Humam Helfawi - 1 month ago 8
C++ Question

Comparer that takes the wanted attribute

In order to use a standard function like

std::sort
on some standard container
Container<T>


struct T{
int x,y;
};


based on the
y
value, you need to write something like (for example):

std::vector<T> v;
//fill v
std::sort(v.begin(),v.end(),[](const auto& l,const auto& r){
return l.y<r.y;
});


The comparer that was written as lambda function is used too much and re-written again and again during the code for various classes and attributes.

Considering the case where
y
's type is comparable (either like
int
or there is an overload for the
< operator
), is there any way to achieve something like:

std::sort(v.begin(),v.end(),imaginary::less(T::y)); // Imaginary code


Is it possible in C++ to write such a function like
less
? or anything similar?

I am asking because I remember something like that in some managed language (I am not sure maybe C# or Java). However, I am not sure even about this information if it is true or not.

Answer
template<typename T, typename MT>
struct memberwise_less
{
    MT T::* const mptr;
    auto operator()(const T& left, const T& right) const
    { return (left.*mptr) < (right.*mptr); }
};

template<typename T, typename MT>
memberwise_less<T, MT> member_less(MT T::*mptr)
{
    return { mptr };
}

and then you can do

std::sort(v.begin(), v.end(), member_less(&T::y));
Comments