Vector addition operation
Solution 1
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 :>
Solution 2
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
Solution 3
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]);
Solution 4
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.
Solution 5
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.
Arpit
Updated on July 26, 2020Comments
-
Arpit almost 4 years
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.
-
Kornel Kisielewicz almost 14 years+1: for noting the other problem that everyone else (including myself) seemed to overlook :D
-
saccharine over 11 yearsNice, much cleaner than double for loop iteration I was using. Any idea if this way is actually faster?
-
greyfade over 11 years@saccharine: It should be as fast as the best loop you can write. All of the work in
std::transform
happens by the magic of templates, so it gets heavily optimized and inlined, and should produce exactly the same object code as a naïve loop.