Push_back a variable to vector

 ̄綄美尐妖づ 提交于 2020-01-05 08:08:30

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/13129292/push-back-a-variable-to-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!