如何删除八叉树c ++的节点(节点为0x4。)

时间:2016-05-16 11:06:29

标签: c++ octree

我有一个八叉树,我必须删除它所搜索的节点的分支。该程序可以找到节点,但我很难删除它。当我创建一个Octree的对象并创建一些节点但我不删除它们时,析构函数就删除了八叉树:

Octree::~Octree()
{
clear(root);
}

void Octree::clear(node *node){
for (int i = 0; i < 8; i++)
    if (node->child[i])
        clear(node->child[i]);

delete node;
}

但是当我想用这种方法删除一个具体的节点时,

void Octree::deletebranch(int branch) {
node *n = search(branch);
if (n) {
    for (int i = 0; i < 8; i++) {
        if (n->child[i]) {
            delete n->child[i];
            n->child[i] = NULL;
        }
    }
    delete n;
    n = NULL;
}
else {
    printf("There is nothing to delete here");
}
}

析构函数调用后我得到了一个异常。   抛出异常:读取访问冲突。    节点是0x4。

我一步一步地调试,发现了一些奇怪的事情。当我创建节点时,我这样做:

        n = new node;
        n->value = xvalue;
        for (int i = 0; i < 8; i++)
            n->child[i] = NULL;

没关系,我设置了值,节点的值是xvalue,子节点是NULL。但是在用deletebranch()方法删除了那个节点后,我的节点发生了这样的变化。

  • n 0x00500788 {value = 0 child = 0x0050078c {0x00000004 {value = ??? child = 0x00000008 {???,???,???,???,???,...}},...}} Octree :: node *     值0 int
  • child 0x0050078c {0x00000004 {value = ??? child = 0x00000008 {???,???,???,???,???,???,???,???}},0xfdfdfdfd {...},...}八叉树:: node * [8]
  • [0] 0x00000004 {value = ??? child = 0x00000008 {???,???,???,???,???,???,???,???}} Octree :: node *
  • [1] 0xfdfdfdfd {value = ??? child = 0xfdfdfe01 {???,???,???,???,???,???,???,???}} Octree :: node *
  • [2] 0xdddddddd {value = ??? child = 0xdddddde1 {???,???,???,???,???,???,???,???}} Octree :: node *
  • [3] 0x29122f71 {value = ??? child = 0x29122f75 {???,???,???,???,???,???,???,???}} Octree :: node *
  • [4] 0x0000a9bd {value = ??? child = 0x0000a9c1 {???,???,???,???,???,???,???,???}} Octree :: node *
  • [5] 0x004d5228 {value = 5249384 child = 0x004d522c {0x005007a0 {value = 5067304 child = 0x005007a4 {0x004fe218 {...},...}},...}} Octree :: node *
  • [6] 0x004fe218 {value = 5244832 child = 0x004fe21c {0x004d00c4 {value = 5235224 child = 0x004d00c8 {0x00501968 {...},...}},...}} Octree :: node *
  • [7] 0xdddddddd {value = ??? child = 0xdddddde1 {???,???,???,???,???,???,???,???}} Octree :: node *
  • 这个0x0043f818 {root = 0x005006b0 {value = 0 child = 0x005006b4 {0x00000000,0x00000000,0x00000000,...}}}八叉树*

我真的不明白为什么会这样,因为我删除它后从未更改过节点。 而且我认为这就是我在析构函数中得到异常的原因。我该如何删除节点?也许尝试捕捉?

这是头文件:

class Octree
{ 
public:
struct node
{
    int value;
    node *child[8];
};

Octree();
~Octree();

void clear(node* node);
int convert(int sorszam);
node* searchandset(int dec, int value);
node *search(int dec);
node* step(node *node, int k);
void Print(node *n)const;
void put(int branch, int value);
void deletebranch(int branch);
node *root;
};

0 个答案:

没有答案