blob: c00b1b499838b0e0650fff3d9e8be3c673fe664b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
#pragma once
#include "../std/vector.hpp"
#include "../std/algorithm.hpp"
template <class T>
class SimpleTree
{
typedef std::vector<SimpleTree<T> > internal_container_type;
T m_value;
internal_container_type m_siblings;
public:
SimpleTree(T const & value = T()) : m_value(value)
{
}
/// @return reference is valid only up to the next tree structure modification
T const & Value() const
{
return m_value;
}
/// @return reference is valid only up to the next tree structure modification
T & Value()
{
return m_value;
}
/// @return reference is valid only up to the next tree structure modification
T & AddAtDepth(int level, T const & value)
{
SimpleTree<T> * node = this;
while (level-- > 0 && !node->m_siblings.empty())
node = &node->m_siblings.back();
return node->Add(value);
}
/// @return reference is valid only up to the next tree structure modification
T & Add(T const & value)
{
m_siblings.push_back(SimpleTree(value));
return m_siblings.back().Value();
}
/// Deletes all children and makes tree empty
void Clear()
{
m_siblings.clear();
}
bool operator<(SimpleTree<T> const & other) const
{
return Value() < other.Value();
}
/// sorts siblings independently on each level by default
void Sort(bool onlySiblings = false)
{
std::sort(m_siblings.begin(), m_siblings.end());
if (!onlySiblings)
for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it)
it->Sort(false);
}
SimpleTree<T> const & operator[](size_t index) const
{
return m_siblings.at(index);
}
size_t SiblingsCount() const
{
return m_siblings.size();
}
template <class TFunctor>
void ForEachSibling(TFunctor & f)
{
for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it)
f(*it);
}
template <class TFunctor>
void ForEachSibling(TFunctor & f) const
{
for (typename internal_container_type::const_iterator it = m_siblings.begin(); it != m_siblings.end(); ++it)
f(*it);
}
template <class TFunctor>
void ForEachChildren(TFunctor & f)
{
for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it)
{
f(*it);
it->ForEachChildren(f);
}
}
template <class TFunctor>
void ForEachChildren(TFunctor & f) const
{
for (typename internal_container_type::const_iterator it = m_siblings.begin(); it != m_siblings.end(); ++it)
{
f(*it);
it->ForEachChildren(f);
}
}
};
|