From 5ac5bd1f43267559c4f1d497eecef58e3398b206 Mon Sep 17 00:00:00 2001 From: Simon Bruder Date: Sat, 22 Apr 2023 11:43:39 +0200 Subject: [PATCH] u01: Add stream output to node --- u01/main.cpp | 3 +++ u01/node.cpp | 12 ++++++++++++ u01/node.h | 3 +++ u01/tests.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+) diff --git a/u01/main.cpp b/u01/main.cpp index 70b6657..701b5c6 100644 --- a/u01/main.cpp +++ b/u01/main.cpp @@ -1,7 +1,10 @@ +#include + #include "node.h" int main(int argc, char **argv) { node *t = create_complete_tree(2, 4); + std::cout << *t; delete t; t = nullptr; node *root = new node("root"); diff --git a/u01/node.cpp b/u01/node.cpp index 3be22e4..1209553 100644 --- a/u01/node.cpp +++ b/u01/node.cpp @@ -32,6 +32,18 @@ node *node::get_child(std::size_t i) const { return children[i]; } void node::add_child(node *child) { children.push_back(child); } +void node::print(std::ostream &str, std::size_t depth) const { + str << std::string(depth, '\t') << get_name() << std::endl; + for (node *child : children) { + child->print(str, depth + 1); + } +} + +std::ostream &operator<<(std::ostream &os, node &n) { + n.print(os); + return os; +} + node *create_complete_tree(std::size_t nr_child_nodes, unsigned int tree_depth) { node *n = new node(); diff --git a/u01/node.h b/u01/node.h index 34db8e2..f991a00 100644 --- a/u01/node.h +++ b/u01/node.h @@ -13,6 +13,7 @@ public: unsigned int get_nr_children() const; node *get_child(std::size_t i) const; void add_child(node *child); + void print(std::ostream &str, std::size_t depth = 0) const; private: std::string name; @@ -20,4 +21,6 @@ private: static unsigned int node_id; }; +extern std::ostream &operator<<(std::ostream &os, node &n); + node *create_complete_tree(std::size_t nr_child_nodes, unsigned int tree_depth); diff --git a/u01/tests.cpp b/u01/tests.cpp index f9cb13e..96c1adf 100644 --- a/u01/tests.cpp +++ b/u01/tests.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "node.h" @@ -111,3 +112,41 @@ TEST_CASE("Create complete tree") { delete t; } + +TEST_CASE("Print complete tree") { + const std::size_t nr_child_nodes = 2; + const unsigned int tree_depth = 4; + node *t = create_complete_tree(nr_child_nodes, tree_depth); + + int count = get_node_id(t); + + std::stringstream output; + t->print(output); + + std::stringstream expected; + expected << "node_" << count++ << std::endl; + for (size_t i = 0; i < 2; i++) { + expected << "\tnode_" << count++ << std::endl; + for (size_t j = 0; j < 2; j++) { + expected << "\t\tnode_" << count++ << std::endl; + for (size_t k = 0; k < 2; k++) { + expected << "\t\t\tnode_" << count++ << std::endl; + } + } + } + REQUIRE(output.str() == expected.str()); + + delete t; +} + +TEST_CASE("Print stream overload") { + node n("foo"); + + std::stringstream output1; + n.print(output1); + + std::stringstream output2; + output2 << n; + + REQUIRE(output1.str() == output2.str()); +}