简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM