I am trying to populate a vector which is a member to an object's class within the constructor. I received a vector index out of bounds error at runtime. I then stepped into the program while it was running using the debugger to see why this error came up. Apparently the vector never was initialized even though i have done so in the constructor. I have my code snippets below, I have added comments to make it more understandable. Any help is greatly appreciated.
Here is the maze.h code snippet
class maze { public: int numlevels, numrows, numcols; int startlevel, startrow, startcol, endlevel, endrow, endcol; int level, row, col; // here is the construtor declaration maze(int l, int m, int n, int o, int p, int q, int r, int s, int t); ~maze(); //these two lines can be ignored void solve(int startlevel, int startrow, int startcol, int endlevel, int endrow, int endcol); queue<char> q; //I declare the 3d array here as a public member vector<vector<vector<string> > > mazeGraph; }; here is the maze.cpp code snippet
//here is the constructor body maze::maze(int l, int m, int n, int o, int p, int q, int r, int s, int t) { numlevels = l; numrows = m; numcols = n; startlevel = 0; startrow = p; startcol = q; endlevel = r; endrow = s; endcol = t; //ignore the redundancy of these assignments for now. //i try to initialize the array here vector<vector<vector<string> > > mazeGraph(numlevels, vector<vector<string> >(numrows, vector<string>(numcols, "0"))); } here is the part of the source .cpp where the error occurs
for (f = 0; f < numMazes; i++) { //these variables are read from a text file and are used to initialize an object's vector member. //nothing is wrong with the file reading, these variables are updated correctly infile >> numlevels >> numrows >> numcols; infile >> startlevel >> startrow >> startcol; infile >> endlevel >> endrow >> endcol; //mazeList is an array of maze objects. each maze object has its own 3 dimensional array which i am trying to initialize with the above variables. mazeList.push_back(maze(numlevels,numrows,numcols,startlevel,startrow,startcol,endlevel,endrow,endcol)); //mazeList.at(f).numlevels refers to the numlevels member belonging to the fth maze object in the list of mazes. //this is the same for numrows and numcols //these member variables are updated corretly for (i = 0; i < mazeList.at(f).numlevels; i++) { for (j = 0; j < mazeList.at(f).numrows; j++) { for (k = 0; k < mazeList.at(f).numcols; k++) { //the text file contains strings that are to be put into a 3-d array //mazeGraph is the 3-d vector belonging to the current maze object //mazeList.at(f).mazeGraph refers to the mazeGraph belonging to the current maze in the list. infile >> mazeList.at(f).mazeGraph[i][j][k]; //the above line generates the error } } }
for (f = 0; f < numMazes; i++)-- You do see that there is an issue here?