Given the code below which just adds 1 to each element of a vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
// Create vector 1 - print it out
std::vector<int> v1 {1,2,3,4,5,6,7,8,9};
for (auto val : v1)
{
std::cout << val << " ";
}
std::cout << std::endl;
// Create vector 2 by a transform of vector 1 + 1
std::vector<int> v2(v1.size());
std::transform(v1.begin(), v1.end(), v2.begin(),
[](int val){ return val + 1; });
// Print out vector 2
for (auto val : v2)
{
std::cout << val << " ";
}
std::cout << std::endl;
}
Instead of just adding 1 to each value I want to add the value of the previous element so that:
v[0] = v[0] (no previous value)
v[1] = v[1] + v[0]
v[2] = v[2] + v[1]
etc...
So that I end up with:
1 = 1
2 + 1 = 3
3 + 2 = 5
4 + 3 = 7
etc...
Its a silly example - its not a maths puzzle or anything like that, I am just trying to figure out if I can use other values in my vector other then the one passed into the lambda function?
I am missing two bits of data in the lambda:
std::transform(v1.begin(), v1.end(), v2.begin(), [](int val){
// What is the index of val?
// What is the size of the vector v1?
// How would I express this:
if (INDEX_OF(val) > 0)
return val + INDEX_OF(val - 1);
else
return val;
});
I can pass v1 in by capture and use that to do some calculations, but not quite what I want since I don't know the index.
std::transform(v1.begin(), v1.end(), v2.begin(),
[&v1](int val){ return val + v1.size() - v1[0]; });
Maybe transform is not the tool for this job and I need to resort to iterator loop?:
std::vector<int> v2(v1.size());
auto it2 = v2.begin();
for (auto it1 = v1.begin(); it1 != v1.end(); it1++, it2++)
{
std::distance(v1.begin(), it1) == 0 ? *it2 = *it1 : *it2 = *it1 + *(it1 - 1);
}
This works, but the point of my question is to know if it can be done with std::transform, or maybe some other algorithm?