The question is quite dumb, but I need to do it in a very efficient way – it will be performed over an over again in my code. I have a function that returns a vector, and I have to add the returned values to another vector, element by element. Quite simple:
vector<double> result;
vector<double> result_temp
for(int i=0; i< 10; i++) result_temp.push_back(i);
result += result_temp //I would like to do something like that.
for(int i =0; i< result_temp.size();i++)result[i] += result_temp[i]; //this give me segfault
The mathematical operation that I’m trying to do is
u[i] = u[i] + v[i] for all i
What can be done?
Thanks
EDIT: added a simple initialization, as that is not the point. How should result be initialized?
If you are trying to append one
vectorto another, you can use something like the following. These are from one of my utilities libraries–twooperator+=overloads forstd::vector: one appends a single element to thevector, the other appends an entirevector:If you are trying to perform a summation (that is, create a new
vectorcontaining the sums of the elements of two othervectors), you can use something like the following:You could similarly implement an
operator+=overload.