Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Created September 11, 2015 22:16
Show Gist options
  • Save daniel-j-h/0d0facf09e9bf43e3625 to your computer and use it in GitHub Desktop.
Save daniel-j-h/0d0facf09e9bf43e3625 to your computer and use it in GitHub Desktop.
sortBy (greater `on` age)
#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