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

标签 sorting c++11 boost-range range-v3

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

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

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

最佳答案

当传递容器参数时,range-v3 中的 view::zip 创建一个由原始元素引用元组组成的 View 。将压缩 View 传递给 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';
}

输出:

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

Live Example on Coliru .

关于对 Range-v3 压缩容器进行排序 - 我可以解压吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417263/

相关文章:

c - 保存数据时出错,数据无效

python-3.x - 在切片上使用递归进行错误的冒泡排序;列表最终没有排序

c++ - 使用OpenCv的矩阵运算(加法和减法)OpenCV C++

c++ - 在循环中附加范围

c++ - 过滤范围、lambda 和 is_sorted

java - 如何按升序对数字数组列表进行排序

c# - List<>.OrderBy() 是否检查列表是否已排序?

C++ 创建一个 char* 迭代器

c++ - 如何检查 vector 的 vector 是否存在?

c++ - 这是 Visual Studio 2013 update 4 C++ 优化器错误还是我的代码有误?