-1

//Max function is working as intended while the minElev is inserting a huge negative value when it hits the final column of the first row. Not sure what is going on and how to fix....

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;
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • Is the matrix a square? If not `a.size()` probably won't cut it for both dimensions. Depending on what `a` is, `a.size()` might not cut it at all. Hard to say for sure what exactly is wrong here. This code might be perfect and you have a small army of dancing gremlins wrecking havoc a few lines before the code you've shown us starts. You can probably salvage this question with a [mre]. – user4581301 Sep 09 '20 at 01:25
  • Posted below hopefully that makes it more clear? :) – Chris Deal Sep 09 '20 at 01:27
  • Much more clear. `for(int j = 0; j < a.size(); j++)` needs to be `for(int j = 0; j < a[i].size(); j++)`. This will run `j` from zero to the size of the row `vector` stored at at `a[i]`, whatever size it is. – user4581301 Sep 09 '20 at 01:42
  • And there's me breaking the rules and answering in a comment. One moment, please... – user4581301 Sep 09 '20 at 01:42

1 Answers1

0

j looks like it's allowed to go out of bounds. Crom only knows what value the program will read if it is outside the storage allocated to the vector, if it reads anything at all. To prevent this

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

needs to be changed to

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

This change will run j from zero to the size of the row vector stored at at a[i].

user4581301
  • 33,082
  • 7
  • 33
  • 54