调试断言失败向量下标超出范围 C++ [英] Debug Assertion Failed Vector Subscript Out of Range C++

查看:87
本文介绍了调试断言失败向量下标超出范围 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 VS2015 C++.我尝试读取文件并使用 while 循环将其逐行输入到向量中.

I am using VS2015 C++. I tried reading a file and inputing it line by line into a vector using a while loop.

我收到此错误:

调试断言失败!

程序:C:\Windows\SYSTEM32\MSVCP140D.dll

Program: C:\Windows\SYSTEM32\MSVCP140D.dll

文件:c:\program files (x86)\microsoft visual studio 14.0\vc\include\vector

File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\vector

行:1234

表达式:向量下标超出范围

Expression: vector subscript out of range

有关您的程序如何导致断言失败的信息,请参阅有关断言的 Visual C++ 文档.

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

我的代码如下:

int main() {
std::ifstream inf("walmart2.txt");

std::vector<std::string> blah;
int j = 0;

if (!inf) {
    std::cerr<< "Uh oh, walmart2.txt could not be opened for reading!" << std::endl;
    exit(1);
}
while (inf)
{
    std::string strInput;
    inf >> strInput;
    blah[j] = strInput;
    j = j + 1;
}

std::cout << blah.size() << '\n';

return 0;
}

文件walmart2.txt"大约有 1800 行,格式如下:

The file "walmart2.txt" is around 1800 lines in the following format:

53.74
54.09
53.5
53.72
53.43

我不完全确定发生了什么.任何帮助表示赞赏.

I'm not entirely sure whats going on. Any help is appreciated.

推荐答案

blah[j] = strInput;

这是未定义的行为,因为blah 是空的.这意味着编译器可以让程序做任何事情.

This is undefined behaviour because blah is empty. Which means the compiler can make the program do anything.

当使用正确的设置进行编译时,Visual C++ 会利用 C++ 标准中未定义的行为来实际检测错误并向您显示此错误消息.

When compiling with the right settings, Visual C++ makes use of that undefined behaviour in the C++ standard in order to actually detect the bug and show you this error message.

改用 push_back 修复错误:

blah.push_back(strInput);

这篇关于调试断言失败向量下标超出范围 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆