如何解决'vector subscript out of range'错误?

How to solve 'vector subscript out of range' error?

本文关键字:of out range 错误 subscript vector 解决 何解决      更新时间:2023-10-16

我正在尝试使用C++学习神经网络,并找到了一个关于数字识别的教程,但是当我运行代码时,我收到一个错误,说"调试断言失败,矢量下标超出范围。显然问题出在loadTraining功能上,但不知道如何修改它以消除错误。

void loadTraining(const char *filename, vector<vector<double>> &input, vector<vector<double>> &output) 
{
int trainingSize = 946;
input.resize(trainingSize);
output.resize(trainingSize);
ifstream file(filename);
if(file) 
{
string line;
int n;
for (int i=0 ; i<trainingSize ; i++) // load 946 examples
{
for (int h=0 ; h<32 ; h++) // 'images' are 32*32 pixels
{
getline(file, line);
for (int w=0 ; w<32 ; w++)
{
input[i].push_back(atoi(line.substr(w,1).c_str()));
}
}
getline(file, line);
output[i].resize(10); // output is a vector of size 10
n = atoi(line.substr(0,1).c_str());
output[i][n] = 1; // set index that represent the number to 1, other are automatically 0 because of the resize()
}
}
file.close();
}

该文件由 32*32 个二进制数字数组组成。 这是一个培训示例。

我正在使用Visual Studio 2013。

考虑使用std::stoi而不是atoi。将std::stoi附在try中并catch块以检查转换问题。还要检查是否n >= 0 && n < 10以解决潜在的下标错误。