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

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c++ - How to add element by element of two STL vectors?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...