C++20 range algorithms support projections, and obviously like STL algorithms they support custom comparators.
But what I found puzzling is the order of the projection and the comparator.
My "problem"(more of a annoyance, I will quickly learn to use this order of arguments) is that it breaks the left to right flow of code.
Consider the following code (apologies for it not being short, but that is kind of the point, to show that in realistic code order of arguments makes code harder to read when your variables names are not 2 letter long):
struct PointyPoint {
int x;
int y;
};
struct Item {
std::string name;
PointyPoint location;
};
//...
std::ranges::sort(
items,
[](const PointyPoint &a, const PointyPoint &b) {
return std::tie(a.x, a.y) < std::tie(b.x, b.y);
},
&Item::location);
Issue I have with this code is that I think it would look much nicer if projection was before the lambda (comparator).
Full code godbolt.
Reasons why I can think this order was picked:
- STL algorithms have comparator usually as 3rd argument(first after the iterators) so it is to match that
- maybe custom comparators are much more common that projection, so to avoid need for supplying that argument