Search code examples
c++vectorpush-back

Storing variables in a vector using push_back


I'm trying to store partial sums in a vector, using push_back and a for loop, however push_back causes an infinite loop for some reason.

cin >> n;

vector <int> partialSums(n);

for (i = 1; i <= partialSums.size(); ++i) {
    sum = sum + i;
    partialSums.push_back(sum);
    cout << sum << endl;
}

return 0;

Solution

  • You create the vector with a specific size (n elements). But then you use push_back which adds new elements and resize the vector. That means partialSums.size() will increase each iteration and you will have your infinite loop.

    Either use i - 1 as an index to set the elements:

    partialSums[i - 1] = sum;
    

    Or just reserve the capacity needed.

    Or, as mentioned in a comment, use i <= n as the condition, as n doesn't change in the loop.