简体   繁体   中英

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++

if (l > length(a)) {
  a <- c(a, a + a[length(a)])
}

Here a is a sequence and l is an integer. 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)].

In C++ I have:

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.

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, (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 :

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM