调试断言失败.C++向量下标超出范围

Abh*_*ain 9 c++ vector

以下代码在第一个for循环中用10个值填充向量.在第二个for循环中我想要打印矢量元素.输出直到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;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*zKP 12

不管你怎么索引你的载体包含索引的10种元素的回送0(0,1,... 9).因此,在你的第二个循环v[j]是无效的,当j10.

这将修复错误:

for(int j = 9;j >= 0;--j)
{
    cout << v[j];
}
Run Code Online (Sandbox Code Playgroud)

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

for(int i = 0;i < 10;++i)
{
    v.push_back(i);
}
Run Code Online (Sandbox Code Playgroud)

另外,要访问容器的元素,惯用方法是使用迭代器(在本例中:反向迭代器):

for (vector<int>::reverse_iterator i = v.rbegin(); i != v.rend(); ++i)
{
    std::cout << *i << std::endl;
}
Run Code Online (Sandbox Code Playgroud)


bil*_*llz 5

v具有10元件,该指数从开始09.

for(int j=10;j>0;--j)
{
    cout<<v[j];   // v[10] out of range
}
Run Code Online (Sandbox Code Playgroud)

你应该更新for循环

for(int j=9; j>=0; --j)
//      ^^^^^^^^^^
{
    cout<<v[j];   // out of range
}
Run Code Online (Sandbox Code Playgroud)

或者使用反向迭代器以相反的顺序打印元素

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}
Run Code Online (Sandbox Code Playgroud)