简体   繁体   中英

2D object array in c++?

2D arrays such as: Cell **scoreTable .After allocating:

scoreTable = new Ceil*[10]; 
for(int i = 0 ;i<10;i++) 
scoreTable[i] = new Ceil[9]; 

And I want to save the value like this: scoreTable[i][j]= new Ceil(i,j) in heap,and this can not work in c++.Thanks for help.

scoreTable[i][j]= new Ceil(i,j) . You are trying to put Cell* into Cell.

You have to create 2d array of pointers:

auto scoreTable = new Ceil**[10]; 
for(int i = 0 ;i<10;i++) 
    scoreTable[i] = new Ceil*[9]; 

But much better is to use vector :

std::vector< std::vector<Ceil*> > table;
table.resize(10);
for (int i = 0; i < 10; ++i)
{
    table[i].resize(9, NULL);
}
table[3][4] = new Ceil();

Once you've allocated your array like this, you'll already have a 2D array of Cell , so you don't need to use the new keyword to change the value.

If you give your Cell class a method like SetValue(i,j) , then you can use it like this: scoreTable[i][j].SetValue(i,j);

I want to suggest using std::vector instead. It is much easier to keep track of.

You can replace all of the code above with

std::vector< std::vector< Cell> > scoreTable(10, std::vector<Cell>(9));

This will create scoreTable , which is a vector containing 10 elements of vector<Cell> , each containing 9 cells. In other word, the desired 2D table.

You access the elements in the same way. scoreTable[i][j] , where i goes fron 0 to 9, and j from 0 to 8.

If you want to expand with a new row, just say:

 scoreTable.push_bach(std::vector<Cell>(9));

For a new column:

for(size_t row = 0; row < scoreTable.size(); ++row) {
  scoreTable[row].push_back(Cell());
}

No need for new or delete .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM