简体   繁体   English

在类中动态分配对象指针的二维数组

[英]Dynamically allocating a 2D array of object pointers in a class

I'm struggling at the moment with the idea of dynamically allocating arrays at runtime.我目前正在为在运行时动态分配数组的想法而苦苦挣扎。 Coming from Java, used to just declaring the arrays in the class skeleton and only needing the size in the implementation.来自Java,过去只在类骨架中声明数组,在实现中只需要大小。

This is what I've found to dynamically allocate 2D arrays:这是我发现动态分配二维数组的方法:

Grid.h   
Block** grid;

Grid.cpp
grid = new Block*[size]
for(int i = 0 ; i < size ; i++)
    grid[i] = new Block[size]

This works pretty okay, although dealing with objects I've always been told that using pointers to objects rather than storing the objects themselves is much better performance wise.这工作得很好,尽管处理对象我总是被告知使用指向对象的指针而不是存储对象本身在性能方面要好得多。 So when I tried to make the second dimension of arrays pointers like this:因此,当我尝试使数组指针的第二维像这样:

Grid.cpp
grid = new Block*[size]
    for(int i = 0 ; i < size ; i++)
        grid[i] = new Block*[size];

When I changed my code to this, I got an error:当我将代码更改为此时,出现错误:

error: assigning to 'Block *' from incompatible type 'Block **'; dereference with *
        grid[i] = new Block* [size];
                ^ ~~~~~~~~~~~~~~~~~
                  *

Being slightly new to the C++ ways of doing things, can someone tell me what I'm doing wrong?对 C++ 的做事方式有点陌生,有人能告诉我我做错了什么吗? Or even if I'm trying to do the wrong thing entirely?或者即使我试图完全做错事?

Thanks in advance!提前致谢!

I would not recommend you writing this type of code, but if you still want to hack your way out you can do something like this:-我不建议你写这种类型的代码,但如果你仍然想破解你的出路,你可以做这样的事情:-

int main()
{
Block*** grid;      

grid = new Block**[10];         
for(int i = 0 ; i < 10 ; i++)
{       
    grid[i] = new Block*[10];   
}

/*Here, we have created a grid of pointers*/

/*

|Block**[10]|

|Block[0] **|------------->|Block* [10]|
|Block[1] **|------------->|Block* [10]|
|Block[2] **|------------->|Block* [10]|
|Block[3] **|------------->|Block* [10]|
..
..
|Block[9] **|------------->|Block* [10]|

*/

for(int i = 0 ; i < 10 ; i++)
{       
    for(int j = 0 ; j < 10 ; j++)
    {
        grid[i][j] = new Block[10]; 
    }
}

/*

|Block**[10]|

|Block[0] **|------------->|Block* [0]|------------->|Block1|Block2| .. |Block10|
                           |Block* [1]|------------->|Block1|Block2| .. |Block10|
                           |Block* [2]|------------->|Block1|Block2| .. |Block10|
                           ..
                           |Block* [9]|------------->|Block1|Block2| .. |Block10|


|Block[1] **|------------->|Block* [0]|------------->|Block1|Block2| .. |Block10|
                           |Block* [1]|------------->|Block1|Block2| .. |Block10|
                           |Block* [2]|------------->|Block1|Block2| .. |Block10|
                           ..
                           |Block* [9]|------------->|Block1|Block2| .. |Block10|          
|Block[2] **|
|Block[3] **|
..
..
|Block[9] **|

*/
 }

A dynamic 2D array is an array of pointers to arrays.动态二维数组是指向数组的指针数组。 You should initialize first the array of pointer, then the others array using a loop.您应该首先初始化指针数组,然后使用循环初始化其他数组。

Here an example using int that creates an array[rowCount][colCount]:这是一个使用 int 创建数组 [rowCount][colCount] 的示例:

int** array = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
    array[i] = new int[colCount];

otherwise of course you can always have a 2D array on the stack by using:否则当然你总是可以通过使用在堆栈上有一个二维数组:

int array[rowCount][colCount];

Use a linear representation of 2d array:使用二维数组的线性表示:

std::unique_ptr<int[]> array(new int[rowCount*colCount]);

for (size_t r = 0; r < rowCount; r++)
  for (size_t c = 0; c < colCount; c++)
    (array.get())[r*colCount + c] = r*c;

Alocating array of pointers can also be done in thread safe manner:分配指针数组也可以以线程安全的方式完成:

size_t allocatedRows = rowCount;
        try{
            array = new char*[allocatedRows];
            while(allocatedRows){
                --allocatedRows;
                array[allocatedRows] = new char[colCount];
            }
        }catch(std::bad_alloc& ex){
            while(++allocatedRows < lines)
                delete array[allocatedRows];
            delete array;
            throw;
        }

Two thing to note in code above:上面代码中有两点需要注意:
1) allocatedRows is not decremented in [] operator, as behaviour would be undefined 1) 分配行在 [] 运算符中不会递减,因为行为将是未定义的
2) After allocating array of pointers, dereferencing array elemnts has undefined behaviour(just like normal pointer without assignment). 2) 分配指针数组后,解引用数组元素有未定义的行为(就像没有赋值的普通指针一样)。 Please also keep in mind that in case above I didn't recovered from bad_alloc I just rethrowed, It can be logged somewhere else before call to termination.还请记住,在上述情况下,我没有从 bad_alloc 中恢复,我只是重新抛出,它可以在调用终止之前记录在其他地方。 If You would like to create array of pointers from other user defined objects You could use std::uninitialized_copy or std::uninitialized_fill.如果您想从其他用户定义的对象创建指针数组,您可以使用 std::uninitialized_copy 或 std::uninitialized_fill。 Another way would be just to use vectors.另一种方法是使用向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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