调试声明失败. C矢量下标超出范围

前端之家收集整理的这篇文章主要介绍了调试声明失败. C矢量下标超出范围前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码在第一个for循环中填充10个值的向量.在第二个循环中,我想要打印矢量的元素.
输出直到j循环之前的cout语句.向量下标的误差超出范围.
  1. #include "stdafx.h"
  2. #include "iostream"
  3. #include "vector"
  4. using namespace std;
  5.  
  6. int _tmain(int argc,_TCHAR* argv[])
  7. { vector<int> v;
  8.  
  9. cout<<"Hello India"<<endl;
  10. cout<<"Size of vector is: "<<v.size()<<endl;
  11. for(int i=1;i<=10;++i)
  12. {
  13. v.push_back(i);
  14.  
  15. }
  16. cout<<"size of vector: "<<v.size()<<endl;
  17.  
  18. for(int j=10;j>0;--j)
  19. {
  20. cout<<v[j];
  21. }
  22.  
  23. return 0;
  24. }

解决方法

无论您如何索引推回,您的矢量包含从0(0,1,…,9)索引的10个元素.所以在你的第二个循环中,v [j]无效,当j为10时.

这将修复错误

  1. for(int j = 9;j >= 0;--j)
  2. {
  3. cout << v[j];
  4. }

一般来说,最好将索引考虑为0,因此我建议您将您的第一个循环更改为:

  1. for(int i = 0;i < 10;++i)
  2. {
  3. v.push_back(i);
  4. }

猜你在找的C&C++相关文章