排序Range-v3压缩的容器-我可以解压缩吗? [英] Sorting Range-v3-zipped containers - can I unzip?

查看:103
本文介绍了排序Range-v3压缩的容器-我可以解压缩吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用C ++ Range-v3库解压缩以前压缩的矢量?我希望它的行为类似于Haskell的解压缩函数或Python的 zip(* list).

Is it possible to unzip previously zipped vectors using the C++ Range-v3 library? I would expect it to behave similarly to Haskell's unzip function or Python's zip(*list).

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

It would be convenient, for instance, when sorting a vector by values of another vector:

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);

推荐答案

在传递容器参数时,范围v3中的view::zip创建一个视图,该视图由对原始元素的引用元组组成.将压缩视图传递到sort可以对元素进行排序.即,该程序:

When passed container arguments, view::zip in range-v3 creates a view consisting of tuples of references to the original elements. Passing the zipped view to sort sorts the elements in place. I.e., this program:

#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';
}

输出:


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上的实时示例 .

这篇关于排序Range-v3压缩的容器-我可以解压缩吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆