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

标签 c++ neural-network pattern-recognition

我正在尝试使用 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::stoitrycatch block 以检查转换问题。还要检查 n >= 0 && n < 10解决潜在的下标错误。

关于c++ - 如何解决 'vector subscript out of range' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187787/

相关文章:

java - 神经网络训练

c++ - 删除指针而不是变量

c++ - 是否强制要求短路逻辑运算符?以及评估顺序?

c++ - 删除/释放由 malloc 分配并由 new 重用的内存

python - 设置 GLOG_minloglevel=1 以防止在 shell 中从 Caffe 输出

opencv - OpenCV 2.2 PCA和EigenFaces

c++ - C++ 中的高效 vector 运算符/对临时对象的引用

python - 如何对张量的每个切片运行迭代 2D 卷积?

c++ - OpenCV 中的旋转和缩放不变模板匹配

MATLAB fitcSVM 权重向量