resizing a 2D vector of structs
Hello, I'm working on making a minesweeper game using C++ but I'm having trouble re sizing a vector.
Here's what I have:
A vector of ints:
Code:
vector<vector<int> > mineField;
A vector of structs:
Code:
struct cell{
int value; //(-1 mine, 0 no surrounding, # > 0 number of surrounding mines)
int state; //( 0 hidden, 1 revealed, 2 marked)
bool isMine;
};
vector<vector<cell> > mineField;
The vector of cell is located in a separate .cpp file of a minesweeper class.
What I want to do is re size the vector of cell to have the same dimensions as the vector of ints.
and initialize the struct variable *value* to the values in the vector of ints and the struct
variable *state* to 0.
This is what I have tried so far:
Code:
this->mineField.resize(rowNum, vector<cell>(colNum));
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
this->mineField[i][j].state = 0;
this->mineField[i][j].value = mineField[i][j];
}
}
When attempt to run this I am only able to have the dimensions 5 rows x 5 columns (I cannot figure out why). Any
other dimensions exits the program and netbeans tells me the run has failed.
I have also tried:
Code:
this->mineField.clear();
for (int i = 0; i < rowNum; i++){
this->mineField.push_back(vector<cell>(colNum, 0));
}
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
this->mineField[i][j].state = 0;
this->mineField[i][j].value = mineField[i][j];
}
}
When trying to resize this way, nothing works.
And this way:
Code:
this->mineField.resize(rowNum);
for(int i = 0; i < rowNum; i++){
this->mineField[i].resize(colNum);
}
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
this->mineField[i][j].state = 0;
this->mineField[i][j].value = mineField[i][j];
}
}
Attempting this lets the program run but doesn't work for any dimensions combination.
Any help is greatly appreciated, thank you.
Re: resizing a 2D vector of structs
Code:
this->mineField[i][j].value = mineField[i][j];
What is this->mineField[] as opposed to mineField[] ? :confused:
Re: resizing a 2D vector of structs
Why not simply create a new one and copy the content of old vector to new and then free the old vector . Any internally resize is also going to do this only.