From cb0d4f52071409a02cb3fbb0180f41f32e5bc3a6 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Fri, 26 Jul 2024 01:49:51 +0100 Subject: Added helper method to allocate nodes from the vector for me The vector acts as an arena for the nodes to be allocated from, better and faster than allocating each child on the heap individually. --- src/main.cpp | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/main.cpp b/src/main.cpp index e89a418..fb29a93 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -87,6 +87,13 @@ struct Node }; std::vector nodes; + +Node *alloc_node(Node n) +{ + nodes.push_back(n); + return nodes.data() + (nodes.size() - 1); +} + std::queue to_iterate; void iterate(void) @@ -97,17 +104,15 @@ void iterate(void) to_iterate.pop(); if (!node->left) { - Node new_node = Fraction{node->value.numerator, - node->value.numerator + node->value.denominator}; - nodes.push_back(new_node); - node->left = nodes.data() + (nodes.size() - 1); + node->left = + alloc_node(Fraction{node->value.numerator, + node->value.numerator + node->value.denominator}); } else if (!node->right) { - Node new_node = Fraction{node->value.numerator + node->value.denominator, - node->value.denominator}; - nodes.push_back(new_node); - node->right = nodes.data() + (nodes.size() - 1); + node->right = + alloc_node(Fraction{node->value.numerator + node->value.denominator, + node->value.denominator}); } to_iterate.push(node->left); to_iterate.push(node->right); -- cgit v1.2.3-13-gbd6f