Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
194 views
Welcome To Ask or Share your Answers For Others

1 Answer

It sure looks like the problem is accessing values of result that don't exist. tzaman shows how to initialize result to 10 elements, each with value 0.

Now you need to call the transform function (from <algorithm>), applying the plus function object (from <functional>):

std::transform(result.begin(), result.end(), result_temp.begin(),
               result.begin(), std::plus<double>());

This iterates over result and result_temp, applies plus that adds doubles, and writes the sum back to result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...