Hello community, Happy New Year!
I came up with interesting macro which allows sort objects by some field. The code is laconic but requires C++11. Macro itself:
#define by(T, x) [](const T& a, const T& b) { return a.x < b.x; }
Usage:
struct Item {
int a, b;
};
sort(arr, arr + N, by(Item, a));
Full example: http://pastebin.com/Cp5ZkwE4.
Happy New Year!
UPD: It was pointed out (in Russian discussion) that C++14 allows shorter version:
#define by(x) [](const auto& a, const auto& b) { return a.x < b.x; }
sort(arr, arr + N, by(a));
It is very useful! Thank you :)
Auto comment: topic has been updated by BekzhanKassenov (previous revision, new revision, compare).
Just for the fun, it is possible to do the same in c++03 without using any macro. It is not as short macro version, but at least you can't break it by passing something like
x || 3
to it.One can go even further and do smth like this:
(decltype is to avoid manual typing of the type name)
Then one can write: