如何用C创建的指针数组++ [英] How to create array of pointers in C++
问题描述
在类节点
:
类节点{
上市:
int数据;
INT numchild;
节点**节点列表; 节点(int数据,int类型);
};
我要指针(节点列表
)到其他节点,其中有从该节点的边缘。
是构建这样一个数组(并宣布它上面的方法),正确的和最佳(或最简单的)可能的方式的下列方式?如果不是,为什么和最新最好的方法是什么?
节点::节点(INT D,int类型){
数据= D;
numchild =秒;
节点列表=新节点* [S]。
}
通常你不应该推倒重来。原阵列几乎总是错的路要走。看一看从STL的各种容器,即的std ::矢量
,的std ::列表
。我woud想在你的情况下,的std ::矢量
可能是最好的解决方案。
如果你想坚持与原阵,一个快速的警告:新节点* [S]
不初始化数组,这样的内容将是不确定的。但是,如果你添加一组括号(新节点* [S]()
)将被初始化为零这是一件好事,因为它可以帮助你发现哪些条目有已经被填满。
另外,你目前的code缺乏析构函数再次删除[]
的节点列表。这正是为什么推荐使用标准容器:他们有析构函数,将做的工作适合你。
In class Node
:
class Node {
public:
int data;
int numchild;
Node** nodelist;
Node(int data, int s);
};
I want an array of pointers (nodelist
) to other nodes, which have edges from this node.
Is the following way of constructing such an array (and the above way of declaring it) a correct and the best (or easiest) way possible? If not, why and whats the best way?
Node::Node(int d, int s) {
data = d;
numchild = s;
nodelist = new Node*[s];
}
Generally you shouldn't reinvent the wheel. Raw arrays are almost always the wrong way to go. Have a look at the various containers from the STL, i.e. std::vector
, std::list
. I woud guess that in your case a std::vector
might be the best solution.
If you want to stick with the raw array, a quick warning: new Node*[s]
does not initialize the array, so the contents will be undefined. But if you add a set of parentheses (new Node*[s]()
) it will be initialized to zero which is a good thing as it helps you spot which entries have been filled already.
Also, your current code lacks a destructor to delete[]
the nodelist again. That's exactly why the use of standard containers is recommended: they have destructors that will do the work for you.
这篇关于如何用C创建的指针数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!