LoginSignup
7
6

More than 5 years have passed since last update.

複数メンバ変数をキーにソート処理

Last updated at Posted at 2014-10-03

http://qiita.com/piyo7/items/e23670cd89502680649c より。

sort_by.hpp
#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...);
  });
}
demo_sort_by.cpp
#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;
}

実行結果:

--sort vector by x
057
048
156
138
246
237
--sort array by (z,y)
246
156
237
057
138
048 

備考:std::tie()operator<の動きについてはこのへん

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6