开发者

Vector addition operation

I am trying to add two Vectors below is the code snippet :-

#include <iostream>
#include <vector>
using namespace std;

int main()
{
        unsigned int i = 0;
        vector <float> v1;
        vector <float> v2;
        vector <float> v3;



        cout << "Filling the Numbers\n";
        for (i=5;i < 125 ; i = i + 5) {
            v1.push_back(i/10);
            v2.push_back(i/100);
     开发者_JS百科   }

        cout << "Adding the numbers\n";
        for (i = 0; i < v1.size(); i++) {
                v3[i] = v1[i] + v2[i];
        }

        cout << "Printing the numbers\n";
                for (i = 0; i < v3.size() ; i++) {
                        cout << v3[i];
                }


        return 0;
}

The program is crashing at Line 18. It seems to me I need to do operator overloading for + operation. Please help.


To avoid the obvious pitfalls you encountered, you can do this as an alternative:

#include <algorithm> // for transform
#include <functional> // for plus

std::transform(v1.begin(), v1.end(), v2.begin(), std::back_inserter(v3), std::plus<float>());

Reference: https://en.cppreference.com/w/cpp/algorithm/transform


This line doesn't work, because there's no v3[i] allocated:

v3[i] = v1[i] + v2[i];

You have two choices, either use 'push_back'

v3.push_back( v1[i] + v2[i] );

Or resize the array to the given size before hand:

v3.resize( v1.size() );

If you push_back, it will be nice to preallocate the space anyway:

v3.reserve( v1.size() );

And finally, you can try to read up on std::valarray instead, as those operations are already built into it!

Edit: and yes, as Johannes noted, you have a problem with floating point division :>


First you need to do a floating point division

v1.push_back(i/10.0f);
v2.push_back(i/100.0f);

Then you need to have space for i variables on v3 or use push_back

v3.push_back(v1[i] + v2[i]);


v3[i] = v1[i] + v2[i];

You are assigning to elements that do not exist. Try v3.push_back(v1[i] + v2[i]); instead.

Also, you probably want i/10.0 instead of i/10, otherwise your results are rounded.


You write into the v3 vector, but you haven't allocated any space for it.

Try to add:

 v3.reserve (v1.size());

between your first and second loop.


I think the problem is v3[i] doesn't work as the vector starts off having zero elements. What you want to do is either:

v3.push_back( v1[i] + v2[i] );

or preallocate the vector

v3.resize( v1.size() );

OR the final solution, which I would do is

v3.reserve( v1.size() );

for (i = 0; i < v1.size(); i++) {
    v3.push_back( v1[i] + v2[i] );
}

as this avoid resizing the vector again and again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜