以下代码在第一个for循环中填充10个值的向量.在第二个循环中,我想要打印矢量的元素.
输出直到j循环之前的cout语句.向量下标的误差超出范围.
输出直到j循环之前的cout语句.向量下标的误差超出范围.
- #include "stdafx.h"
- #include "iostream"
- #include "vector"
- using namespace std;
- int _tmain(int argc,_TCHAR* argv[])
- { vector<int> v;
- cout<<"Hello India"<<endl;
- cout<<"Size of vector is: "<<v.size()<<endl;
- for(int i=1;i<=10;++i)
- {
- v.push_back(i);
- }
- cout<<"size of vector: "<<v.size()<<endl;
- for(int j=10;j>0;--j)
- {
- cout<<v[j];
- }
- return 0;
- }
解决方法
无论您如何索引推回,您的矢量包含从0(0,1,…,9)索引的10个元素.所以在你的第二个循环中,v [j]无效,当j为10时.
这将修复错误:
- for(int j = 9;j >= 0;--j)
- {
- cout << v[j];
- }
一般来说,最好将索引考虑为0,因此我建议您将您的第一个循环更改为:
- for(int i = 0;i < 10;++i)
- {
- v.push_back(i);
- }