Advertisement
donkaban

Untitled

Nov 29th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. class node :
  2.         public std::enable_shared_from_this<node>
  3. {
  4. public:
  5.     using ptr  = std::shared_ptr<node>;
  6.     using cref = const ptr &;
  7.  
  8.     void add_child(cref n)
  9.     {
  10.         if(std::find(childs.begin(), childs.end(), n) != childs.end()) return;
  11.         auto par = n->parent.lock();
  12.         if(par)
  13.             par->remove_child(n);
  14.         n->parent = shared_from_this();
  15.         childs.push_back(n);
  16.     }
  17.     void remove_child(cref n)
  18.     {
  19.         if(n)
  20.         {
  21.             childs.erase(std::remove(childs.begin(), childs.end(), n), childs.end());
  22.             n->parent.reset();
  23.         }
  24.     }
  25.     ptr get_child(size_t n)
  26.     {
  27.         return childs.at(n);
  28.     }
  29.     void set_parent(cref n)
  30.     {
  31.         auto par = parent.lock();
  32.         if (par == n || !n)
  33.             return;
  34.         n->add_child(shared_from_this());
  35.     }
  36. private:
  37.     std::weak_ptr<node> parent;
  38.     std::vector<ptr>    childs;
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement