Search code examples
c++vectorpush-back

Push_back a variable to vector


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.


Solution

  • 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;
    }