代码之家  ›  专栏  ›  技术社区  ›  HiroIshida

c中带列表的树数据结构++

  •  0
  • HiroIshida  · 技术社区  · 7 年前

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

    具体来说,我怀疑“std::list lst_nodes”的必要性。 tree类中的expand_node函数将新节点附加到父节点,父节点的值最接近新节点的值。这个过程需要在所有现有节点上迭代来访问它们的值。为了这个迭代的目的,我在树类中定义了一个名为“std::list lst_nodes”的成员变量。我认为,在不定义LSTSB节点的情况下,可能存在同样的方法。

    #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();
      }
    }
    

    谢谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Olivier Sohn    7 年前

    在现代C++中,可以使用 unique_pointer<T> 而不是生的 T* 当指向的对象由具有指针的对象拥有时的指针。这样,你就不用解释了 delete 对象,它将在 unique_ptr 毁灭者。

    在一棵树中(即一个没有循环的连通图),所有权是明确定义的:每个节点都拥有它的子节点,因此您可以使用 list<unique_ptr<Node>> 对于 Node::children 是的。