加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:03:08 所属栏目:百科 来源:网络整理
导读:以下代码在第一个for循环中填充10个值的向量.在第二个循环中,我想要打印矢量的元素. 输出直到j循环之前的cout语句.向量下标的误差超出范围. #include "stdafx.h"#include "iostream"#include "vector"using namespace std;int _tmain(int argc,_TCHAR* argv[
以下代码在第一个for循环中填充10个值的向量.在第二个循环中,我想要打印矢量的元素.
输出直到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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读