This is the error message in question: terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create Aborted
This is the code that triggers it. This section in the main.cpp file:
case '-': // DeleteItem
try
{
int id;
inputs >> id;
Student s(id, "NULL", "NULL");
cout << "DeleteItem('" << id << "') -- ";
s = tPtr->DeleteItem(s);
cout << "Deleted ";
s.Print();
}
It never gets past tPtr->DeleteItem(s), and this is the code involved for DeleteItem(s). DeleteItem function:
template <typename SomeType>
SomeType BSTree<SomeType>::DeleteItem(SomeType item){
if (rootPtr == NULL){
throw EmptyBSTree();
}
Delete(rootPtr, item);
cout<<"done"<<endl;
}
Delete function:
template <typename SomeType>
void BSTree<SomeType>::Delete(BSTreeNode<SomeType>*& treePtr, SomeType& item){
if (treePtr->data == item){
DeleteNode(treePtr);
cout<<"done2"<<endl;
}
else{
if (item<treePtr->data){
if (treePtr->leftPtr != NULL){
Delete(treePtr->leftPtr, item);
}
else{
throw NotFoundBSTree();
}
}
else{
if (treePtr->rightPtr != NULL){
Delete(treePtr->rightPtr, item);
}
else{
throw NotFoundBSTree();
}
}
}
DeleteNode function:
template <typename SomeType>
void BSTree<SomeType>::DeleteNode(BSTreeNode<SomeType>*& treePtr){
cout<<"here"<<endl;
BSTreeNode<SomeType>* temp = new BSTreeNode<SomeType>;
temp = treePtr;
if (treePtr->leftPtr == NULL && treePtr->rightPtr == NULL){
delete temp;
}
else{
if (treePtr->leftPtr == NULL){
treePtr = treePtr->rightPtr;
delete temp;
}
else if (treePtr->rightPtr == NULL){
treePtr = treePtr->leftPtr;
delete temp;
}
else{
treePtr->data = GetPredecessor(treePtr->leftPtr);
Delete(treePtr->leftPtr,treePtr->data);
}
}
cout<<"I am here"<<endl;
}
I find this very strange as all cout statements I put to make sure the code gets to that line are all outputted to the terminal, so it exits both functions, but it never gets past the original line in main.cpp. I'm super confused on why I keep getting that error.
EDIT: This problem was solved by adding a return to DeleteItem. However I ran into another problem. Delete doesn't seem to work here:
template <typename SomeType>
void BSTree<SomeType>::DeleteNode(BSTreeNode<SomeType>*& treePtr){
BSTreeNode<SomeType>* temp;
temp = treePtr;
if (treePtr->leftPtr == NULL && treePtr->rightPtr == NULL){
delete temp;
cout<<"This is "<<treePtr->data<<endl;
}
else{
if (treePtr->leftPtr == NULL){
treePtr = treePtr->rightPtr;
delete temp;
}
else if (treePtr->rightPtr == NULL){
treePtr = treePtr->leftPtr;
delete temp;
}
else{
treePtr->data = GetPredecessor(treePtr->leftPtr);
Delete(treePtr->leftPtr,treePtr->data);
}
}
}
Tree Ptr should be deleted but it prints out This is (random number). Why?