Sayonara Player
Loading...
Searching...
No Matches
Tree.h
1
2/* Copyright (C) 2011-2024 Michael Lugmair (Lucio Carreras)
3 *
4 * This file is part of sayonara player
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#ifndef TREE_H
21#define TREE_H
22
23#include <QList>
24#include <algorithm>
25
26namespace Util
27{
28 template<typename T>
33 class Tree
34 {
35 public:
36 Tree* parent = nullptr;
37 T data;
38 QList<Tree*> children;
39
40 Tree() :
41 Tree(T {}) {}
42
43 explicit Tree(const T& data) :
44 parent(nullptr),
45 data(data) {}
46
47 ~Tree()
48 {
49 for(auto* child: children)
50 {
51 delete child;
52 child = nullptr;
53 }
54
55 children.clear();
56 data = T();
57 }
58
65 {
66 node->parent = this;
67
68 this->children << node;
69 this->sort(false);
70
71 return node;
72 }
73
74 Tree* addChild(const T& data)
75 {
76 auto* node = new Tree(data);
77 return addChild(node);
78 }
79
85 Tree* removeChild(Tree* deletedNode)
86 {
87 auto it = std::find_if(children.begin(), children.end(), [&](const auto* node) {
88 return (node == deletedNode);
89 });
90
91 if(it != children.end())
92 {
93 auto* node = *it;
94 children.erase(it);
95 node->parent = nullptr;
96 return node;
97 }
98
99 return nullptr;
100 }
101
106 void sort(bool recursive)
107 {
108 if(children.isEmpty())
109 {
110 return;
111 }
112
113 auto lambda = [](auto* tree1, auto* tree2) {
114 return (tree1->data < tree2->data);
115 };
116
117 std::sort(children.begin(), children.end(), lambda);
118
119 if(recursive)
120 {
121 for(auto* child: children)
122 {
123 child->sort(recursive);
124 }
125 }
126 }
127 };
128}
129
130#endif // TREE_H
Definition: EngineUtils.h:33
The Tree class.
Definition: Tree.h:34
void sort(bool recursive)
sort children of all nodes in ascending way according to their data
Definition: Tree.h:106
Tree * addChild(Tree *node)
adds a child to the given node
Definition: Tree.h:64
Tree * removeChild(Tree *deletedNode)
remove a node from the current node
Definition: Tree.h:85
Helper functions.
Definition: MetaTypeRegistry.h:25