问题
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