Useful macro

Revision en2, by BekzhanKassenov, 2015-12-28 18:31:44

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) [](auto a, auto b) { return a.x < b.x; }
sort(arr, arr + N, by(a));
Tags c++, macro, sort

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English BekzhanKassenov 2015-12-29 09:39:19 14 Tiny change: ' by(x) [](auto a, auto b) { retu' -> ' by(x) [](const auto& a, const auto& b) { retu'
ru4 Russian BekzhanKassenov 2015-12-29 09:39:03 14
en2 English BekzhanKassenov 2015-12-28 18:31:44 190
ru3 Russian BekzhanKassenov 2015-12-28 18:30:15 168
ru2 Russian BekzhanKassenov 2015-12-28 15:35:14 9 Мелкая правка: 'ртировать классы по опред' -> 'ртировать объекты по опред' (опубликовано)
en1 English BekzhanKassenov 2015-12-28 15:34:46 422 Initial revision for English translation
ru1 Russian BekzhanKassenov 2015-12-28 15:32:07 503 Первая редакция (сохранено в черновиках)