Created
September 11, 2015 22:16
-
-
Save daniel-j-h/0d0facf09e9bf43e3625 to your computer and use it in GitHub Desktop.
sortBy (greater `on` age)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <ostream> | |
#include <algorithm> | |
#include <iterator> | |
#include <functional> | |
#include <type_traits> | |
struct Person { | |
int id; | |
int age; | |
friend std::ostream& operator<<(std::ostream& out, const Person& person) { | |
return out << person.id << ',' << person.age; | |
} | |
}; | |
template <typename Persons> | |
void print(const Persons& persons) { | |
for (auto&& each : persons) | |
std::cout << each << std::endl; | |
endl(std::cout); | |
} | |
template <typename Persons, typename Cmp> | |
void sort(Persons& persons, Cmp cmp) { | |
std::stable_sort(begin(persons), end(persons), cmp); | |
} | |
// https://hackage.haskell.org/package/base-4.8.1.0/docs/Data-Function.html#v:on | |
template <typename Cmp, typename MemPtr> | |
auto inline on(Cmp cmp, const MemPtr memPtr) { | |
static_assert(std::is_member_pointer<MemPtr>(), "requires member pointer"); | |
return [=](const auto& lhs, const auto& rhs) { | |
return cmp(lhs.*memPtr, rhs.*memPtr); | |
}; | |
} | |
int main() { | |
using Persons = std::vector<Person>; | |
Persons persons{{0,1}, {1,3}, {1,2}, {2,0}}; | |
sort(persons, on(std::greater<>{}, &Person::id)); | |
print(persons); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment