Tenncor
tree.hpp
Go to the documentation of this file.
1 
9 #include <functional>
10 #include <iostream>
11 #include <string>
12 
13 #ifndef DBG_TREE_HPP
14 #define DBG_TREE_HPP
15 
16 const char vert_branch = '-';
17 
21 template <typename T>
22 struct PrettyTree final
23 {
26  PrettyTree (std::function<std::vector<T>(T&)> traverser,
27  std::function<void(std::ostream&,T&)> to_stream) :
28  traverser_(traverser), to_stream_(to_stream) {}
29 
33  void print (std::ostream& out, T root)
34  {
35  print_helper(out, root, "");
36  }
37 
39  size_t branch_length_ = 2;
40 
42  std::function<std::vector<T>(T&)> traverser_;
43 
45  std::function<void(std::ostream&,T&)> to_stream_;
46 
47 private:
48  void print_helper (std::ostream& out, T root, std::string prefix)
49  {
50  out << "(";
51  to_stream_(out, root);
52  out << ")\n";
53  std::vector<T> children = traverser_(root);
54  size_t nchildren = children.size();
55  if (nchildren > 0)
56  {
57  std::string branch = prefix + " `" +
58  std::string(branch_length_, vert_branch);
59  for (size_t i = 0; i < nchildren - 1; ++i)
60  {
61  out << branch;
62  this->print_helper(out, children[i],
63  prefix + " |" + std::string(branch_length_, ' '));
64  }
65  out << branch;
66  this->print_helper(out, children[nchildren - 1],
67  prefix + std::string(2 + branch_length_, ' '));
68  }
69  }
70 };
71 
72 #endif // DBG_TREE_HPP
std::function< void(std::ostream &, T &)> to_stream_
Behavior of displaying a node in the structure.
Definition: tree.hpp:45
const char vert_branch
Definition: tree.hpp:16
void print_helper(std::ostream &out, T root, std::string prefix)
Definition: tree.hpp:48
void print(std::ostream &out, T root)
Definition: tree.hpp:33
size_t branch_length_
Horizontal length of the branch, by default the branch looks like `–.
Definition: tree.hpp:39
Definition: tree.hpp:22
std::function< std::vector< T >T &)> traverser_
Behavior of traversing through a structure.
Definition: tree.hpp:42
PrettyTree(std::function< std::vector< T >(T &)> traverser, std::function< void(std::ostream &, T &)> to_stream)
Definition: tree.hpp:26