将变量推回向量 [英] Push_back a variable to vector

查看:29
本文介绍了将变量推回向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始学习 STL,这是第一个问题:

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

如您所见,我想将变量 i 推回向量 vec1,但输出为:

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

5832900
-319008141
0

等等...

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

谢谢你的一切.

推荐答案

你往后推,但打印出 item[i],它是最后一个(我在你的循环中从一个开始).

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

这篇关于将变量推回向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆