我一直在研究基于矢量的avl树很长一段时间。我想从文件中获取输入,但在4118输入时它会给我一个bad_alloc错误。我做了一些研究并收集了我必须保留空间的输入。但即使我确实分配空间,它仍然会给出相同的错误。
我的部分代码:
我称之为此功能:
void insert(T d, unsigned int c = 1);
find(T d)在vector<node<T>*> myVector
中找到newNode的位置;
即使它没有找到newNode,它也会返回一个位置。 Insert将处理返回的整数(如下所示)
插入是:
template<typename T>
void binaryTree<T>::insert(T d, unsigned int c)
//inserts type T with count c into vector
{
node<T>* newNode = new node<T>(d,c);
if(myVector.empty())
{
myVector.push_back(newNode);
}
else
{
int r = find(d);
total++;
//if newNode has same data as the data in position r
if(r < myVector.size() && myVector[r] && *newNode == *myVector[r])
{
myVector[r]->data.loc.push_back(newNode->data.loc[0]);
myVector[r]->count += newNode->count;
delete newNode;
return;
}
//insert into vector normally
else
{
checkSpace(r);
myVector[r] = newNode;
//reParent(r);
}
}
}
使用checkSpace:
template<typename T>
void binaryTree<T>::checkSpace(int i)
//resizes the vector if needed
{
if(i >= myVector.size())
{
myVector.resize(rightOi(i),NULL);
}
}
和void reParent(r)是执行所有旋转和平衡的主要功能。 我注释掉了reParent(r),并且可能已将问题隔离在仅仅插入函数中。我对此很新,我感谢任何帮助。提前谢谢。
rightOi功能:
template<typename T>
//return the right position of i
int binaryTree<T>::rightOi(int i)
{
return i*2 + 2;
}
答案 0 :(得分:0)
我可能错了,而且有点偏离主题,但在我看来,这个向量对于动态树来说不是一个好主意,我会创建树老式的方式,就像这样:
struct Node
{
T value;
Node* right;
Node* left;
}
int main()
{
Node<int>* root = new Node<int>();
root->value = 10;
root->right = NULL;
root->left = NULL;
Node<int>* someNode = new Node<int>();
someNode->value = 5;
someNode->right = NULL;
someNode->left = NULL;
root->left = someNode;
}
因此它可能被包含在AddElement,Rebalance,Traverse,Delete等函数中。询问您是否需要更详细的描述。
答案 1 :(得分:0)
所以我发现了问题,即checkspace()函数(调整向量大小)会使向量调整大小。这就是为什么程序不断给我错误的原因。解决方法是仅在必要时调整大小。这就是我修复项目的方法。