indexed_sort.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright Louis Dionne 2013-2017
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  4. #include <boost/hana/at.hpp>
  5. #include <boost/hana/back.hpp>
  6. #include <boost/hana/core/to.hpp>
  7. #include <boost/hana/front.hpp>
  8. #include <boost/hana/functional/on.hpp>
  9. #include <boost/hana/integral_constant.hpp>
  10. #include <boost/hana/length.hpp>
  11. #include <boost/hana/less.hpp>
  12. #include <boost/hana/pair.hpp>
  13. #include <boost/hana/range.hpp>
  14. #include <boost/hana/sort.hpp>
  15. #include <boost/hana/transform.hpp>
  16. #include <boost/hana/tuple.hpp>
  17. #include <boost/hana/type.hpp>
  18. #include <boost/hana/zip.hpp>
  19. #include <type_traits>
  20. namespace hana = boost::hana;
  21. using namespace hana::literals;
  22. auto indexed_sort = [](auto list, auto predicate) {
  23. auto indexed_list = hana::zip(
  24. list,
  25. hana::to_tuple(hana::make_range(0_c, hana::length(list)))
  26. );
  27. auto sorted = hana::sort.by(predicate ^hana::on^ hana::front, indexed_list);
  28. return hana::make_pair(hana::transform(sorted, hana::front),
  29. hana::transform(sorted, hana::back));
  30. };
  31. int main() {
  32. auto types = hana::tuple_t<char[4], char[2], char[1], char[5], char[3]>;
  33. auto sorted = indexed_sort(types, [](auto t, auto u) {
  34. return hana::sizeof_(t) < hana::sizeof_(u);
  35. });
  36. using Tup = decltype(
  37. hana::unpack(hana::first(sorted), hana::template_<hana::tuple>)
  38. )::type;
  39. auto indices = hana::second(indexed_sort(hana::second(sorted), hana::less));
  40. // When accessed through the indices sequence, the tuple appears to be
  41. // ordered as the `types` above. However, as can be seen in the
  42. // static_assert below, the tuple is actually ordered differently.
  43. Tup tup;
  44. char const(&a)[4] = tup[indices[0_c]];
  45. char const(&b)[2] = tup[indices[1_c]];
  46. char const(&c)[1] = tup[indices[2_c]];
  47. char const(&d)[5] = tup[indices[3_c]];
  48. char const(&e)[3] = tup[indices[4_c]];
  49. static_assert(std::is_same<
  50. Tup,
  51. hana::tuple<char[1], char[2], char[3], char[4], char[5]>
  52. >{}, "");
  53. (void)a; (void)b; (void)c; (void)d; (void)e;
  54. }