I often find myself wanting to create a comparator objects for a struct or class which simply extracts one member of the class and does the usual < comparison on that.
For example:
struct student {
int id;
std::string name;
}
// sort by ID
std::sort(students.begin(), students.end(), [](const student& l, const student& r){ return l.id < r.id; });
There's a lot of boilerplate there, in particular because we have to repeat the declaration for l and r. Is there a way in the standard library to create a comparator based on an "extractor" function which returns an object to compare on?
Something like:
std::sort(students.begin(), students.end(), compare_on([](const student& s){ return s.id; });
I'm using C++11, but also interested if there are solutions in later standards that don't apply in C++11 (so I can add something to my "reasons to upgrade" list).
Aucun commentaire:
Enregistrer un commentaire