Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of C++ Adding Doubles of Elements in Vectors without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
Trying to debug this code, where given a vector {1,2}, it should print out {1,2,2,4}. However, I’m getting an infinte loop.
Here is the code:
#include <iostream> #include <vector> using namespace std; void Add_Doubles(vector<int> & A){ for (int i=0; i< A.size(); i++) A.push_back(2*A[i]); } void print (const vector<int> & A){ for (int i=0; i<A.size(); i++) cout << A[i] <<" "; cout << endl; } int main(){ vector<int> A; A.push_back(1); A.push_back(2); Add_Doubles(A); print(A); Add_Doubles(A); print(A); return 0; }
I feel that it’s the for loop not exiting, but it might be something else. Any pointers would help!
Answer
When you push_back
a new integer to A, its size increases. That means you’ll never reach the end of your loop. I suggest you store the initial size of it in an another integer like so:
int myVecSize = A.size();
and then compare that with i.
We are here to answer your question about C++ Adding Doubles of Elements in Vectors - If you find the proper solution, please don't forgot to share this with your team members.