aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2024-07-26 01:49:51 +0100
committerAryadev Chavali <aryadev@aryadevchavali.com>2024-07-26 02:54:02 +0100
commitcb0d4f52071409a02cb3fbb0180f41f32e5bc3a6 (patch)
tree44ff20a475ea65a9c89558f10cd30f99709c9c72
parentee1cc0816a2b429952562953d1e1d3768d4c741a (diff)
downloadcw_tree-cb0d4f52071409a02cb3fbb0180f41f32e5bc3a6.tar.gz
cw_tree-cb0d4f52071409a02cb3fbb0180f41f32e5bc3a6.tar.bz2
cw_tree-cb0d4f52071409a02cb3fbb0180f41f32e5bc3a6.zip
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.
-rw-r--r--src/main.cpp21
1 files changed, 13 insertions, 8 deletions
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<Node> nodes;
+
+Node *alloc_node(Node n)
+{
+ nodes.push_back(n);
+ return nodes.data() + (nodes.size() - 1);
+}
+
std::queue<Node *> 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);