views:

69

answers:

6

Hi, 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);
        }

        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 I am new to C++.

Thanks Arpit

A: 

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.

FredOverflow
+3  A: 

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]);
Johannes Schaub - litb
+1: for noting the other problem that everyone else (including myself) seemed to overlook :D
Kornel Kisielewicz
+1  A: 

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.

Nils Pipenbrinck
A: 

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.

bramp
+5  A: 

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 valarray instead, as those operations are already built into it!

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

Kornel Kisielewicz
A: 

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(), back_inserter(v3), std::plus);
greyfade