#include <ranges>
#include <algorithm>
#include <vector>
using namespace std;
struct Edge{int from, to;};
const vector<int> v1 = {1, 1} , v2 = {2,2};
vector<Edge> v3 = views::zip( v1, v2) | ranges::to<vector>();
使用 g++14 编译。
prog.cc:10:38:错误:请求从“向量
这个问题可以不做就解决吗(冗长得令人痛苦):
#include <ranges>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
struct Edge{int from, to;};
const vector<int> v1 = {1, 1} , v2 = {2,2};
vector<Edge> v3 = views::zip( v1, v2) | views::transform([](const auto arg){const auto [a, b]=arg; return Edge{a,b};}) | ranges::to<vector>();
}
C++23 带来了 zip_transform,它可以将其简化为这样
#include <ranges>
#include <vector>
#include <iostream>
//using namespace std; //unlearn this
int main()
{
struct Edge
{
static Edge Create(int f,int t)
{
return Edge{f,t};
}
int from;
int to;
};
const std::vector<int> v1 = { 1, 2 };
const std::vector<int> v2 = { 3, 4 };
auto edges = std::views::zip_transform(Edge::Create,v1,v2) | std::ranges::to<std::vector>();
for(const auto& edge : edges)
{
std::cout << "edge : from " << edge.from << " to" << edge.to << "\n";
}
return 0;
}