C++ 中带有列表的树数据结构

tree data structure with list in c++

本文关键字:数据结构 列表 C++      更新时间:2023-10-16

我在 c++ 中实现了树结构,引用了其他人的代码。我下面的代码肯定是编译的,似乎运行良好。但我怀疑有更好的方法。例如,此代码在内存泄漏点是否安全?有没有更简单、计算效率更高的方法?

具体来说,我怀疑"std::list lst_nodes"的必要性。 Tree 类中的 expand_node 函数将新节点附加到父节点,该父节点的值最接近新节点的值。此过程需要迭代所有现有节点才能访问其值。出于此迭代目的,我在树类中定义了一个名为"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