如何解决'vector subscript out of range'错误?
How to solve 'vector subscript out of range' error?
我正在尝试使用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
以解决潜在的下标错误。
相关文章:
- 为什么我的向量::擦除调用会抛出"vector subscript out of range"?
- 解决方案在第 25 行执行错误'out of bounds'
- C++ 向量加减抛出"expression: vector subscript out of range."错误
- 从 MSVC14 切换到 MSVC16 会导致"compiler is out of heap space (C1060)"错误
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 如何解决'vector subscript out of range'错误?
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 空集"Out of bound iterator"
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- 注册 Clang 检查器时出错:"out-of-line-definition of register"
- QList::operator[]中的断言失败<T>:QJoysticks 中的"index out of range"
- 尝试获取矩阵的正确对角线会导致"vector out of range"错误
- 运算符方法和返回对象"out-of-scope"?
- 如何使用 mpi 分散修复"vector subscript out of range"?
- 如何修复邻接列表中的"Debug Assertion Failed" "vector subscript out of range"
- "Vector subscript out of range",在返回声明?
- QList<T>::operator[]: "index out of range" 中的断言失败
- 多次调用存储过程时C++连接器"Commands out of sync" mySQL
- 如何处理C++'index out of bounds error'?
- MySQL 异常"connection lost during query"、"MySQL server has gone away"和"command out of sync"