对 Range-v3 压缩容器进行排序 - 我可以解压吗?

2024-03-26

是否可以使用 C++ 解压之前压缩的向量Range-v3 库 https://github.com/ericniebler/range-v3?我希望它的行为与 Haskell 类似unzip http://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude.html#v:unzip函数或Python的邮编(*列表) https://stackoverflow.com/a/12974504/4932728.

例如,当根据另一个向量的值对向量进行排序时,这会很方便:

using namespace ranges;

std::vector<std::string> names {"john", "bob", "alice"};
std::vector<int>         ages  {32,     19,    35};

// zip names and ages
auto zipped = view::zip(names, ages);
// sort the zip by age
sort(zipped, [](auto &&a, auto &&b) {
  return std::get<1>(a) < std::get<1>(b);
});
// put the sorted names back into the original vector
std::tie(names, std::ignore) = unzip(zipped);

当传递容器参数时,view::ziprange-v3 创建一个由原始元素引用元组组成的视图。将压缩视图传递给sort对元素进行适当排序。即这个程序:

#include <vector>
#include <string>
#include <iostream>

#include <range/v3/algorithm.hpp>
#include <range/v3/view.hpp>

using namespace ranges;

template <std::size_t N>
struct get_n {
  template <typename T>
  auto operator()(T&& t) const ->
    decltype(std::get<N>(std::forward<T>(t))) {
      return std::get<N>(std::forward<T>(t));
  }
};

namespace ranges {
template <class T, class U>
std::ostream& operator << (std::ostream& os, common_pair<T, U> const& p) {
  return os << '(' << p.first << ", " << p.second << ')';
}
}

int main() {
  std::vector<std::string> names {"john", "bob", "alice"};
  std::vector<int>         ages  {32,     19,    35};

  auto zipped = view::zip(names, ages);
  std::cout << "Before: Names: " << view::all(names) << '\n'
            << "         Ages: " << view::all(ages) << '\n'
            << "       Zipped: " << zipped << '\n';
  sort(zipped, less{}, get_n<1>{});
  std::cout << " After: Names: " << view::all(names) << '\n'
            << "         Ages: " << view::all(ages) << '\n'
            << "       Zipped: " << zipped << '\n';
}

Outputs:



Before: Names: [john,bob,alice]
         Ages: [32,19,35]
       Zipped: [(john, 32),(bob, 19),(alice, 35)]
 After: Names: [bob,john,alice]
         Ages: [19,32,35]
       Zipped: [(bob, 19),(john, 32),(alice, 35)]
  

Coliru 上的实例 http://coliru.stacked-crooked.com/a/f900939878251ffc.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对 Range-v3 压缩容器进行排序 - 我可以解压吗? 的相关文章

随机推荐