C++ 中带有列表的树数据结构
tree data structure with list in c++
我在 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
。
相关文章:
- 当接收到不明确的规范时,表示图的邻接列表的数据结构
- 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- C++ 中带有列表的树数据结构
- 尝试创建排序的动态列表(数据结构)
- 如何将边缘列表转换为DCEL数据结构
- 如何检索指向列表数据结构中的变量的指针?
- Qt:通过深度复制访问列表中的数据结构是否应该比通过指针访问它慢得多
- 嵌套的C 常数数据结构,没有初始化列表或明确命名所有节点-VC 2012过早破坏了内部元素
- 在C++中,是否可以引用像C++中的stl列表这样的数据结构部分
- C++数据结构列表,在我的代码中
- 列表中的数据结构
- 说 C++ 中的数组或 Python 中的列表是一个类是否正确?数据结构?或两者兼而有之
- 用于处理 3 个整数列表的数据结构
- 如何使用智能指针(例如auto_ptr r shared_ptr)在 Linux 上的C++中生成链接列表数据结构
- 这是一个具有基于数组的列表函数的数据结构项目,我似乎无法摆脱这个无限循环。
- 如何从 CGAL 中的坐标和拓扑列表创建Polyhedron_3数据结构
- 用于存储地址的单列列表的数据结构,更好地在C++中查找O(1)
- 用于存储元组键的数据结构:参数关系列表
- C++数据结构来执行索引列表
- 如何填充数据结构列表