Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparer that takes the wanted attribute

Tags:

c++

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.

like image 496
Humam Helfawi Avatar asked Nov 02 '16 20:11

Humam Helfawi


People also ask

What is ScanIndexForward?

ScanIndexForward. Specifies the order for index traversal: If true (default), the traversal is performed in ascending order; if false , the traversal is performed in descending order. Items with the same partition key value are stored in sorted order by sort key.

What is Expressionattributenames?

An expression attribute name is a placeholder that you use in an Amazon DynamoDB expression as an alternative to an actual attribute name. An expression attribute name must begin with a pound sign ( # ), and be followed by one or more alphanumeric characters.

What is ExclusiveStartKey?

ExclusiveStartKey. Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter.

What is PartiQL?

What is PartiQL? PartiQL provides SQL-compatible query access across multiple data stores containing structured data, semistructured data, and nested data. It is widely used within Amazon and is now available as part of many AWS services, including DynamoDB.


1 Answers

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));
like image 72
Ben Voigt Avatar answered Oct 20 '22 03:10

Ben Voigt