I am creating a binary tree program and I would like to overload a few operators. I have tried overloading the + operator so that when I write something like myTree + 5
, it would add 5 as a node on the tree.
This is my code:
BST myTree;
void operator+(BST left, int right) {
myTree.addLeaf(right);
}
int main() {
vector<int> treeKeyList;
srand((unsigned)time(NULL));
int before = rand() % 20 + 1;
for (int i = 0; i < before; i++) {
int after = rand() % 20 + 1;
treeKeyList.push_back(after);
cout << treeKeyList[i] << " ";
}
cout << endl;
for (int i = 0; i < treeKeyList.size(); i++) {
myTree + treeKeyList[i];
}
}
At the moment, it seems to run fine through one loop, however it crashes when it tries to add the second value with a segmentation fault error. I think the issue must be in the code I have shown, as before I added the overloading it worked fine. If I did this instead:
for (int i = 0; i < treeKeyList.size(); i++) {
myTree.addLeaf(treeKeyList[i]);
}
It works absolutely fine. Any ideas?