我正在尝试使用 C++ 了解神经网络,并找到了有关数字识别的教程,但是当我运行代码时,我收到一条错误消息,提示“调试断言失败, vector 下标超出范围”。显然问题出在 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 个二进制数字数组组成。 This is one training exmple.
我使用的是 visual studio 2013。
最佳答案
考虑使用 std::stoi
而不是 atoi
.附上std::stoi
在try
和 catch
block 以检查转换问题。还要检查 n >= 0 && n < 10
解决潜在的下标错误。
关于c++ - 如何解决 'vector subscript out of range' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187787/