Created
October 5, 2014 08:28
-
-
Save yohhoy/d3c78e817573b4fb1f21 to your computer and use it in GitHub Desktop.
sort by data member in class
This file contains hidden or 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 <algorithm> | |
| #include <iterator> | |
| #include <tuple> | |
| template < | |
| typename Iterator, // RandomAccessIterator | |
| typename... Ts, | |
| typename U = typename std::iterator_traits<Iterator>::value_type> | |
| void sort_by(Iterator begin, Iterator end, Ts U::*... pm) | |
| { | |
| static_assert(0 < sizeof...(Ts), "empty sort key"); | |
| std::sort(begin, end, [&pm...](const U& x, const U& y){ | |
| return std::tie(x.*pm...) < std::tie(y.*pm...); | |
| }); | |
| } | |
| //---- | |
| #include <iostream> | |
| #include <vector> | |
| struct S { int x,y,z; }; | |
| int main() | |
| { | |
| std::vector<S> vs = {{2,4,6}, {2,3,7}, {1,5,6}, {1,3,8}, {0,5,7}, {0,4,8}}; | |
| std::cout << "--sort vector by x" << std::endl; | |
| sort_by(std::begin(vs), std::end(vs), &S::x); | |
| for (auto& e : vs) | |
| std::cout << e.x << e.y << e.z << std::endl; | |
| S as[] = {{2,4,6}, {2,3,7}, {1,5,6}, {1,3,8}, {0,5,7}, {0,4,8}}; | |
| std::cout << "--sort array by (z,y)" << std::endl; | |
| sort_by(std::begin(as), std::end(as), &S::z, &S::y); | |
| for (auto& e : as) | |
| std::cout << e.x << e.y << e.z << std::endl; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment