C ++中2D数组的等效C calloc

问题描述

我找到了关于迷宫生成器的这段代码(C代码),我想在C ++中使用它:

{
    int x,y; //Node position - little waste of memory,but it allows faster generation
    void *parent; //Pointer to parent node
    char c; //Character to be displayed
    char dirs; //Directions that still haven't been explored
} Node;

Node *nodes; //Nodes array
int width,height; //Maze dimensions


int init( )
{
    int i,j;
    Node *n;
    
    //Allocate memory for maze
    nodes = calloc( width * height,sizeof( Node ) );
    if ( nodes == NULL ) return 1;
        
    //Setup crucial nodes
    for ( i = 0; i < width; i++ )
    {
        for ( j = 0; j < height; j++ )
        {
            n = nodes + i + j * width;
            if ( i * j % 2 ) 
            {
                n->x = i;
                n->y = j;
                n->dirs = 15; //Assume that all directions can be explored (4 youngest bits set)
                n->c = ' '; 
            }
            else n->c = '#'; //Add walls between nodes
        }
    }
    return 0;
}

问题来自nodes = calloc( width * height,sizeof( Node ) );行 如何更改C ++代码?我想尽可能避免使用new,因为所有代码都很大。

解决方法

这是C ++,因此将calloc放在一边并使用new[]

Node *n = new Node[width * height];

std::vector:更好,

std::vector<Node> n(width * height);

在两种情况下都一样简单:

auto& node = n[i + j * width];

访问单个元素。

您还需要为Node创建一个适当的构造函数,以设置这些指针,或者至少为它们提供安全的默认值。在这种情况下,将它们添加到矢量中可能会更容易,例如:

 std::vector<Node> n; // Start empty

 // Inside the loops...
 n.emplace_back(i,j,nullptr,' ',15);