u01: Add stream output to node

This commit is contained in:
Simon Bruder 2023-04-22 11:43:39 +02:00
parent 65f13d8780
commit 5ac5bd1f43
4 changed files with 57 additions and 0 deletions

View file

@ -1,7 +1,10 @@
#include <iostream>
#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");

View file

@ -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();

View file

@ -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);

View file

@ -1,5 +1,6 @@
#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <sstream>
#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());
}