1

Just started learning STL and here is the first problem:

  vector<int> vec1;

for(int i = 1; i <= 100; i++)
{
    vec1.push_back(i);
    cout << vec1[i] << endl;
}

As you may see i want to push back variable i to vector vec1 but output is:

5832900
-319008141
0

etc...

Process returned 0 (0x0)   execution time : 0.210 s
Press any key to continue.

Thanks for anything.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268

2 Answers2

3

Your pushing on the back, but printing out item[i], which is one past the end (i starts at one in your loop).

vector<int> vec1;

for(int i = 0; i < 100; i++)
{
    vec1.push_back(i+1);
    cout << vec1[i] << endl;
}
Mark Stevens
  • 2,366
  • 14
  • 9
1

You are printing one beyond the end of the vector each time. This would be a correct version of your code:

for(int i = 0; i < 100; i++)
{
    vec1.push_back(i+1);
    cout << vec1[i] << endl;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480