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

Debug assertion failed. C++ vector subscript out of range

本文关键字:下标 范围 断言 失败 C++ 调试      更新时间:2023-10-16

下面的代码首先用 10 个值填充向量 loop.in 第二个循环我希望打印 vector 的元素。输出直到 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索引的 10 个元素(01、...、9)。所以在你的第二个循环中,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);
}

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

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

v10元素,索引从0开始到9

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

您应该for循环更新为

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

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

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}
当您

尝试通过尚未分配数据数据的索引访问数据时,通常会发生此类错误。例如

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

代码将给出错误(矢量下标超出范围)因为您正在访问尚未分配的 arr[10]。