如何编写使用临时容器的范围管道? [英] How do I write a range pipeline that uses temporary containers?

查看:146
本文介绍了如何编写使用临时容器的范围管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个签名的第三方函数:

I have a third-party function with this signature:

std::vector<T> f(T t);

我也有一个潜在的无限范围(命名为 src / ericniebler / range-v3> range-v3 sort )我想创建一个管道,将 f 映射到该范围的所有元素,并将所有向量平坦化为单个范围及其所有元素。

I also have an existing potentially infinite range (of the range-v3 sort) of T named src. I want to create a pipeline that maps f to all elements of that range and flattens all the vectors into a single range with all their elements.

本能,我会写下如下。

 auto rng = src | view::transform(f) | view::join;

但是,这不会工作,因为我们无法创建临时容器的视图。

However, this won't work, because we cannot create views of temporary containers.

range-v3如何支持这样的范围管道?

How does range-v3 support such a range pipeline?

推荐答案

只是不能。 查看没有任何机制在任何地方存储临时 - 这明确反对从 docs

I suspect it just can't. None of the views have any machinery to store temporaries anywhere - that's explicitly against the concept of view from the docs:


视图是一个轻量级的封装器,在某些自定义方式,而不变异或复制它。视图创建和复制的成本很低,并且具有非拥有引用语义。

因此,为了使 join 某个地方必须坚持这些临时性。这可能是一个行动。这将工作(演示):

So in order for that join to work and outlive the expression, something somewhere has to hold onto those temporaries. That something could be an action. This would work (demo):

auto rng = src | view::transform(f) | action::join;



<即使对于有限的 src 也可能增加了太多的开销,你想要使用。

except obviously not for src being infinite, and even for finite src probably adds too much overhead for you to want to use anyway.

复制/重写 view :: join ,改为使用稍微修改的 view :: all href =https://github.com/ericniebler/range-v3/blob/master/include/range/v3/view/join.hpp#L93>这里),而不是要求一个左值容器(并向其返回一个迭代器对),允许它将在内部存储的一个右值容器(并且将一个迭代器对返回到该存储的版本)。但是这是几百行的复制代码,所以似乎很不满意,即使这样工作。

You would probably have to copy/rewrite view::join to instead use some subtly modified version of view::all (required here) that instead of requiring an lvalue container (and returning an iterator pair into it), allowed for an rvalue container that it would store internally (and returning an iterator pair into that stored version). But that's several hundred lines' worth of copying code, so seems pretty unsatisfactory, even if that works.

这篇关于如何编写使用临时容器的范围管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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