在2D向量迭代中寻找最小值误差

问题描述

// Max函数minelev到达第一行的最后一列时插入一个巨大的负值时正在按预期方式工作。不确定发生了什么以及如何解决。...

bool pathfinder::_read_data(string data_file_name) {
    string string_1 = "",string_2 = "";
    int rows = 0,columns = 0;
    int x = 0;   //Temp Variable
    vector<int> temp;
    vector<vector<int>> a;
    ifstream fileIn(data_file_name);
//    if (!fileIn) {
//        cerr << "Couldn't read this file!!!";
//        return 666;
//    }

    fileIn >> string_1 >> columns >> string_2 >> rows;


    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {

            fileIn >> x;
            temp.push_back(x);

        }
        a.push_back(temp);
        temp.clear();
    }
    int maxElev = a[0][0];
    int minelev = a[0][0];
    for(int i = 0; i < a.size(); i++){
        for(int j = 0; j < a.size(); j++){
            if(a[i][j] > maxElev){
                maxElev = a[i][j];
            }
            if(a[i][j] < minelev){
                minelev = a[i][j];
            }
        }

    }



    // Todo: read in and store elevation data

    // Todo: close input file

    // Todo: return true if everything worked
    return true;
}

解决方法

j似乎被允许越界。如果程序完全读取任何内容,则Crom仅知道该程序在分配给vector的存储器之外时将读取什么值。为了防止这种情况

for(int j = 0; j < a.size(); j++)

需要更改为

for(int j = 0; j < a[i].size(); j++)

此更改将使j从零运行到存储在vector处的行a[i]的大小。