-3

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;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Michel
  • 3
  • 3

1 Answers1

7

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621