[英]Replacing data with range-v3
How is it possible to obtain the same results of怎么可能得到相同的结果
std::copy(std::begin(a), std::end(a), std::begin(b));
using range-v3, and possibly its nice syntax?使用 range-v3,可能还有它不错的语法?
EDIT编辑
The reason I was having troubles is the misunderstanding of how to correctly use ranges::copy
: the second argument must be an iterator , not a range object.我遇到麻烦的原因是对如何正确使用
ranges::copy
的误解:第二个参数必须是迭代器,而不是范围对象。 My fault ;)我的错 ;)
Nevertheless, I am still asking if some sort of syntactic sugar is available to perform a ranged assignment , like the following:尽管如此,我仍然在问是否可以使用某种语法糖来执行ranged assignment ,如下所示:
ranges::???(b) = a | op1 | op2 | ... ;
I have got two fixed size vectors (at runtime).我有两个固定大小的向量(在运行时)。 I need to perform some complex transformation of the data in the first vector and store the results in the second vector.
我需要对第一个向量中的数据执行一些复杂的转换,并将结果存储在第二个向量中。 I need to keep the first vector and I do not want to create a new temporary vector.
我需要保留第一个向量,但不想创建新的临时向量。
using namespace std;
vector<double> a;
...
vector<double> b(a.size());
transform(begin(a), end(a), begin(b), complexFun);
auto transformation = a | ranges::view::transform(complexFun);
copy(begin(transformation), end(transformation), begin(b));
In this simple case, it is a bit unnecessary to do so.在这种简单的情况下,这样做有点不必要。 However, if more than one operation is involved, creating the range view then using
std::copy
is particularly useful.但是,如果涉及多个操作,则创建范围视图然后使用
std::copy
特别有用。
ranges::???(b) = a | ranges::view::transform(complexFun);
What I am expecting is that this feature already exists, and I am not able to find it.我期待的是这个功能已经存在,我无法找到它。
How about:怎么样:
ranges::transform(a, b.begin(), complexfun);
? ?
EDIT: ... or maybe编辑:...或者也许
ranges::copy( a | ranges::views::transform(complexFun), begin(b) );
? ?
There are a couple of good ways to do this.有几种好方法可以做到这一点。 First, if you don't yet have the destination
vector
and you want to create it:首先,如果您还没有目标
vector
并且想要创建它:
auto b = a | ranges::view::transform(complexFun) | ranges::to_vector;
Second, if you already have a destination vector
whose capacity you want to reuse:其次,如果您已经有一个想要重用其容量的目标
vector
:
b.clear(); // Assuming b already contains junk
b |= ranges::action::push_back(a | ranges::view::transform(complexFun));
In both cases, range-v3 is smart enough to reserve capacity in the destination vector for ranges::size(a | ranges::view::transform(complexFun))
elements to avoid copies due to reallocation.在这两种情况下,range-v3 都足够聪明,可以在目标向量中为
ranges::size(a | ranges::view::transform(complexFun))
元素保留容量,以避免由于重新分配而导致复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.