手机版
你好,游客 登录 注册
背景:
阅读新闻

N叉树一 基本实现

[日期:2012-06-17] 来源:Linux社区  作者:sheismylife [字体:大 中 小]

我用的是GCC4.7.0,Ubuntu 12.04,CMake.

现在看看tree.h中的实现。

  1. #ifndef _TREE_H   
  2. #define _TREE_H   
  3.   
  4. #include <vector>   
  5. #include <memory>   
  6.   
  7. namespace freebird {  
  8.   
  9.   template<typename T>  
  10.     class node{  
  11.   public:  
  12.   node(T value):value_(value){  
  13.     }  
  14.   
  15.   
  16.   
  17.     /** 
  18.      * insert child node to the end 
  19.      */  
  20.     void push_back(std::shared_ptr<node<T>> child){  
  21.       children_.push_back(child);  
  22.     }  
  23.   
  24.     typedef typename std::vector<shared_ptr<node<T>>>::iterator iterator_type;  
  25.   
  26.     void insert(iterator_type pos,std::shared_ptr<node<T> > child){  
  27.       children_.insert(pos,child);  
  28.     }  
  29.   
  30.     T value() const {  
  31.       return value_;  
  32.     }  
  33.   
  34.   
  35.     /** 
  36.      * iterator to the first child 
  37.      */  
  38.     iterator_type begin(){  
  39.       return children_.begin();  
  40.     }  
  41.   
  42.     /** 
  43.      * Get the end iterator of children 
  44.      */  
  45.     iterator_type end(){  
  46.       return children_.end();  
  47.     }  
  48.   
  49.   private:  
  50.     T value_;  
  51.   
  52.     std::vector<shared_ptr<node<T>>> children_;  
  53.   };  
  54.   
  55.   
  56.   
  57.   template<typename T>  
  58.     class tree {  
  59.   public:  
  60.     tree<T>(){  
  61.     }  
  62.   
  63.     void root(T node){  
  64.       root_ = node;  
  65.     }  
  66.   
  67.     T root() {  
  68.       return root_;  
  69.     }  
  70.       
  71.   private:  
  72.     T root_;  
  73.   };  
  74. }  
  75.   
  76. #endif  
shared_ptr就在memory头文件中,不再需要加入boost库。

实现还是挺简单的,用了一个vector,里面存放了shared_ptr<node<T>>,因此删除的时候不要手动delete。只是小心不要在树里面节点形成回路,那是shared_ptr最忌讳的。‘

linux
相关资讯       C++  N叉树 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款