如何解决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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。