Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing the size of a vector in for loop

If i increase the size of a std::vector in a for loop when it is a parameter of the for loop, will it work? Will the for loop recalculate the size of the vector on each iteration?

Example:

for(int i=0; i<myVector.size(); i++)
{
   myVector.push_back(new element);
}

Thanks

like image 445
Noobgineer Avatar asked Jan 26 '26 18:01

Noobgineer


1 Answers

Yes, myVector.size() will be re-evaluated on each iteration, returning a larger value each time. Therefore, your loop would never end, because it would be like a dog chasing its own tail (assuming that the initial size is non-zero).

If you would like to double the number of elements in the vector, you need to store myVector.size() upfront, and use the stored value in your loop, like this:

size_t origSize = myVector.size();
for(int i=0; i<origSize; i++)
{
   myVector.push_back(new element);
}
like image 87
Sergey Kalinichenko Avatar answered Jan 28 '26 06:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!