当传递容器参数时,view::zip
在 range-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';
}
输出:
之前:姓名:[约翰,鲍勃,爱丽丝]
年龄:[32,19,35]
压缩:[(john, 32),(bob, 19),(alice, 35)]
之后:姓名:[bob,john,alice]
年龄:[19,32,35]
压缩:[(bob, 19),(john, 32),(alice, 35)]
Coliru 上的实时示例。