我有一个二进制搜索树类,我们需要用静态数组实现它。我的讲师要求我们对插入和删除功能进行错误处理。我试图从重载[]运算符抛出一个错误,并在插入函数中捕获它,然后将其抛给main函数。我的BST保持正整数; -1用于表示空节点。
重载[]运算符
//overloaded [] operator to perform bounds checking of the array and return the value associated to the index
int& BST::operator[](int i)
{
if(i < 0 || i >= BST_SIZE)
{
throw out_of_range("ERROR: BST has reached maximum depth");
}
else
{
return Tree[i];
}
}
//overloaded [] operator to perform bounds checking of the array and return the value associated to the index and also
//allows BST manipulation
const int& BST::operator[](int i) const
{
if(i < 0 || i >= BST_SIZE)
{
throw out_of_range("ERROR: BST has reached maximum depth");
}
else
{
return Tree[i];
}
}
插入功能
//insert function called by main to insert a valid value into the BST
void BST::insert(const int& x)
{
if(Tree[0] == -1)
{
Tree[0] = x;
}
else if(Tree[0] > x)
{
insert(x, 1);
}
else
{
insert(x, 2);
}
}
//recursive insert function called by insert function with one arguement to move through BST
void BST::insert(const int& x, const int& loc)
{
try
{
Tree[loc]; //used to cause throw from [] operator is necessary
}
catch(out_of_range& e)
{
throw e;
}
if(Tree[loc] == -1) //ERROR-> Thread 1: EXC_BAD_ACCESS (code=1, address=0x7fff5fcfd7b4)
{
Tree[loc] = x;
}
else if(Tree[loc] > x)
{
insert(x, (2*loc)+1);
}
else
{
insert(x, (2*loc)+2);
}
}
包含代码用法的主要功能代码段
BST myTree;
try
{
myTree.insert(6);
myTree.insert(2);
myTree.insert(4);
myTree.insert(0);
myTree.insert(9);
myTree.insert(3);
myTree.insert(8);
myTree.insert(76);
myTree.insert(1);
myTree.insert(5);
myTree.insert(99);
myTree.insert(101);
myTree.insert(999);
myTree.insert(11010);
myTree.insert(6859);
myTree.insert(9956);
myTree.display();
}
catch(out_of_range& e)
{
cout << e.what() << endl;
exit(2);
}
目前,当BST在完整时不尝试插入新值时,我的代码将编译并运行。现在我正试图溢出我的BST并捕获错误以确保错误处理工作。我正在使用Xcode 7.2并在第二个插入函数中出现上面的注释错误。在我看来,IDE在抛出之前会抛出错误。