我用c++实现了一个树结构,引用了别人的代码。我编写的下面的代码肯定是经过编译的,而且看起来运行良好。但我怀疑有更好的方法。例如,这段代码在内存泄漏点上是否安全?有没有更简单、计算效率更高的方法?
具体来说,我怀疑“std::list lst_nodes”的必要性。 Tree 类中的 expand_node 函数将新节点附加到其值最接近新节点的父节点。此过程需要迭代所有现有节点以访问它们的值。为了这个迭代目的,我在 Tree 类中定义了一个名为“std::list lst_nodes”的成员变量。我怀疑可能存在一种无需定义 lst_nodes 即可完成相同操作的简洁方法。
#include<random>
#include<iostream>
#include<list>
using namespace std;
class Node{
public:/*functions*/
Node(const double& val_, Node* parent_=nullptr)
:val(val_), parent(parent_)
{
if(parent){
parent->children.push_back(this);
}
}
public:/*variables*/
Node* parent;
std::list<Node*> children;
double val;
};
class Tree{
public:/*function*/
Tree(double x_init);
void extend_node();
public:/*variables*/
list<Node*> lst_nodes;
double x_init;
};
Tree::Tree(double x_init_)
:x_init(x_init_)
{
Node* n=new Node(x_init);
lst_nodes.push_back(n);
}
void Tree::extend_node(){
double val_new = rand();
auto it=lst_nodes.begin();
double minval = abs((**it).val-val_new);
Node* node_parent;
for(;it!=lst_nodes.end(); it++){
if(minval>abs((**it).val-val_new)){
minval = abs((**it).val-val_new);
node_parent = *it;
}
}
Node* n_new = new Node(val_new, node_parent);
node_parent->children.push_back(n_new);
lst_nodes.push_back(n_new);
}
int main(){
Tree t(0);
for(int i=0; i<100; i++){
t.extend_node();
}
}
非常感谢。
最佳答案
在现代 C++ 中,您可以使用 unique_pointer<T>
而不是原始 T*
当指向的对象由具有指针的对象拥有时的指针。这样,您就不必明确 delete
对象,它将在 unique_ptr
中完成析构函数。
在树中(即没有循环的连接图)所有权明确定义:每个节点都拥有其子节点,因此您可以使用 list<unique_ptr<Node>>
对于 Node::children
.
关于c++ - C++中带列表的树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163919/