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.
This line doesn’t work, because there’s no
v3[i]allocated:You have two choices, either use ‘push_back’
Or resize the array to the given size before hand:
If you push_back, it will be nice to preallocate the space anyway:
And finally, you can try to read up on
std::valarrayinstead, as those operations are already built into it!Edit: and yes, as Johannes noted, you have a problem with floating point division :>