dl
dl_tree.h
浏览该文件的文档.
1
14#pragma once
15
16#include <vector>
17
18#include "io/dl_log.h"
19
20namespace dl
21{
22
23template<typename T>
24class NTree
25{
26public:
27 struct Node
28 {
31 std::vector<Node*> _child;
32 Node(const T& v, Node* parent) :
33 _parent{ parent },
34 _v{v}
35 {}
36
38 {
39 return _v;
40 }
42 {
43 return _v;
44 }
45 };
46
48 {}
49
54 Node* Add(const T& v, const T& parent)
55 {
56 if (!parent)
57 {
58 if (!_allNode.empty())
59 {
60 log_err0("根节点已经存在,不能重复添加!");
61 return nullptr;
62 }
63 Node* node = new Node(v, nullptr);
64 _allNode.push_back(node);
65 return node;
66 }
67
68 Node* node_parent = Get(parent);
69 if (!node_parent)
70 {
71 log_err0("父节点不存在!");
72 return nullptr;
73 }
74 Node* node = new Node(v, node_parent);
75 _allNode.push_back(node);
76 node_parent->_child.push_back(node);
77 return node;
78 }
83 {
84 for (Node* node : _allNode)
85 {
86 if (v == node->_v)
87 return node;
88 }
89 return nullptr;
90 }
94 template<typename F>
95 void ForEach(F func)
96 {
97 if (_allNode.empty())
98 return;
99
100 std::stack<Node*> s;
101 s.push(_allNode.front());
102
103 while (!s.empty())
104 {
105 Node* node_this = s.top();
106 s.pop();
107 func(node_this->_v);
108
109 //反向遍历
110 auto& c = node_this->_child;
111 for (auto iter = c.rbegin(); iter != c.rend(); ++iter)
112 {
113 Node* node = *iter;
114 s.push(node);
115 }
116 }
117 }
118
120 auto begin() { return _allNode.begin(); }
121 auto end() { return _allNode.end(); }
122
124 {
125 for (Node* node : _allNode)
126 {
127 delete node;
128 }
129 }
130private:
131 std::list<Node*> _allNode;//所有节点,第一个为根节点
132};
133
134}
NTree()
Definition: dl_tree.h:47
void ForEach(F func)
遍历,保证父节点先遍历
Definition: dl_tree.h:95
auto end()
Definition: dl_tree.h:121
Node * Get(T v)
查找,失败返回nullptr
Definition: dl_tree.h:82
auto begin()
标准库迭代方法不保证父节点先遍历
Definition: dl_tree.h:120
~NTree()
Definition: dl_tree.h:123
Node * Add(const T &v, const T &parent)
添加,parent为nullptr时,为添加根节点
Definition: dl_tree.h:54
日志系统
Definition: dl_array2.h:17
void log_err0(std::string_view str, const std::source_location location=std::source_location::current())
std::vector< Node * > _child
Definition: dl_tree.h:31
T & operator*()
Definition: dl_tree.h:41
Node * _parent
Definition: dl_tree.h:30
T & operator->()
Definition: dl_tree.h:37
Node(const T &v, Node *parent)
Definition: dl_tree.h:32