[英]How to increase the length of a sequence of numbers in vector
I'm trying to make a rewrite the following lines of code of R in C++ 我正在尝试用C ++重写R的以下代码行
if (l > length(a)) {
a <- c(a, a + a[length(a)])
}
Here a is a sequence and l is an integer. 这里a是一个序列,l是一个整数。 I just want to check if l is out of index of a (ie a[l] is not defined), and if so I want to extend the vector by concatenating it with a + a[length(a)].
我只想检查l是否超出a的索引(即a [l]未定义),如果是这样,我想通过将向量与a + a [length(a)]连接来扩展向量。
In C++ I have: 在C ++中,我有:
if (l >= a.size()) {
a.resize(2*a.size());
}
Here I have '>=' since indices start from 0, but I'm not sure how to initialise my new values. 因为索引从0开始,所以这里有'> =',但是我不确定如何初始化新值。
As an example if a = (0.1, 0.2, 0.3) and l = 4, then I want to change a to 例如,如果a =(0.1,0.2,0.3)和l = 4,那么我想将a更改为
a = (0.1, 0.2, 0.3, (0.1+0.3), (0.2+0.3), (0.3+0.3))
= (0.1, 0.2, 0.3, 0.4, 0.5, 0.6)
auto size = a.size();
if (l >= size) {
auto last = a.back();
for (auto i = 0; i < size; ++i)
a.push_back(a[i] + last);
}
Something like the above? 像上面的东西? Tons of variations on this are possible.
对此可能有多种变化。
You might want to consider the possibility that l
is larger than size() * 2
: 您可能要考虑
l
大于size() * 2
的可能性:
while(l >= a.size()) { // loop until l < s.size()
size_t elements = a.size();
auto last_element = a.back();
for(size_t e = 0; e < elements; ++e)
a.push_back(a[e] + last_element);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.