调试断言失败.C++矢量下标超出范围
Debug assertion failed. C++ vector subscript out of range
下面的代码首先用 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 个元素(0
、1
、...、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;
}
v
有10
元素,索引从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]。
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 矢量下标超出SFML游戏中的范围
- 运行时错误:矢量下标超出范围:正在检查空集
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 编译期间矢量下标超出范围
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 对矢量来说是全新的.矢量下标超出范围
- C++十进制到十六进制(字符串下标超出范围)
- 创建结构体向量,表达式:向量下标超出范围
- 读取矢量时矢量下标超出范围
- 断言失败错误,C++中的矢量下标超出范围问题
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 表达式:矢量下标超出范围
- 矢量下标超出范围,带有嵌套的 for 循环
- 向量下标超出向量向量的范围
- gcc8.2如何启用警告:数组下标在数组范围之上[-warray-bounds]
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- C++超出下标范围