Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.38 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. class smart_pointer {
  5.     T* m_obj;
  6. public:
  7.     // Отдаем ему во владение некий объект
  8.     smart_pointer(T* obj)
  9.         : m_obj(obj)
  10.     { }
  11.     // По выходу из области видимости этот объект мы уничтожим
  12.     ~smart_pointer() {
  13.         delete m_obj;
  14.     }
  15.     // Перегруженные операторы<
  16.     // Селектор. Позволяет обращаться к данным типа T посредством "стрелочки"
  17.     T* operator->() { return m_obj; }
  18.     // С помощью такого оператора мы можем разыменовать указатель и получить ссылку на
  19.     // объект, который он хранит
  20.     T& operator* () { return *m_obj; }
  21. };
  22.  
  23. struct BinaryTree
  24. {
  25.     BinaryTree* l = nullptr;
  26.     BinaryTree* r = nullptr;
  27.     int* data = nullptr;
  28.     BinaryTree() {}
  29.     BinaryTree(const int& a);
  30.     void DeleteData();
  31.     void AddNode(const int& a);
  32.     void PrintTree();
  33.     ~BinaryTree();
  34. };
  35.  
  36. BinaryTree::BinaryTree(const int& a) {
  37.     data = new int;
  38.     *data = a;
  39. }
  40.  
  41. void BinaryTree::PrintTree() {
  42.     if (l != nullptr) {
  43.         l->PrintTree();
  44.     }
  45.     if (data != nullptr) {
  46.         std::clog << *data << '\n';
  47.     }
  48.     if (r != nullptr) {
  49.         r->PrintTree();
  50.     }
  51. }
  52.  
  53. void BinaryTree::DeleteData() {
  54.     if (l != nullptr) {
  55.         delete l;
  56.     }
  57.     if (r != nullptr) {
  58.         delete r;
  59.     }
  60.     delete data;
  61.     data = nullptr;
  62.     return;
  63. }
  64.  
  65. void BinaryTree::AddNode(const int& a) {
  66.     if (data == nullptr) {
  67.         data = new int;
  68.         *data = a;
  69.         return;
  70.     }
  71.     if (*data < a) {
  72.         if (r != nullptr) {
  73.             r->AddNode(a);
  74.             return;
  75.         }
  76.         r = new BinaryTree(a);
  77.         return;
  78.     }
  79.     else {
  80.         if (l != nullptr) {
  81.             l->AddNode(a);
  82.             return;
  83.         }
  84.         l = new BinaryTree(a);
  85.         return;
  86.     }
  87. }
  88.  
  89. BinaryTree::~BinaryTree() {
  90.     DeleteData();
  91. }
  92.  
  93. void BalanceTree() {
  94.     //
  95. }
  96.  
  97. int main() {
  98.     int a = 5;
  99.     BinaryTree t(a);
  100.     t.AddNode(6);
  101.     t.AddNode(4);
  102.     t.AddNode(3);
  103.     t.PrintTree();
  104.     std::clog << *t.data << '\n';
  105.     smart_pointer<BinaryTree> kek(new BinaryTree(3));
  106.     return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement