gpt4 book ai didi

c++ - 插入到 2-3-4 树中

转载 作者:行者123 更新时间:2023-11-28 07:06:05 26 4
gpt4 key购买 nike

我目前正在尝试编写一个使用 2-3-4 树的程序,但我遇到了插入函数的问题。这是相关代码..

int main () {

tree234 myTree;
myTree.insert("hello");

myTree.printTree();

return 0;
}

//-------------tree234.cpp-------------
#include "tree234.h"
#include <string>
#include <iostream>

void tree234::insert(string input){
int index;

if (nullRoot == true) {
//insert root
initNode(root);

root->data[0] = input;

nullRoot = false;

return;
}
}

void tree234::initNode(Node* node) {
node = new Node();
node->pointer[0] = NULL;
node->pointer[1] = NULL;
node->pointer[2] = NULL;
node->pointer[3] = NULL;
node->data[0] = "";
node->data[1] = "";
node->data[2] = "";
}

//-----------tree234.h--------------
#ifndef TREE_234_H_
#define TREE_234_H_

using namespace std;
#include <iostream>

class tree234{
private:
struct Node {
public:
string data[3];
Node* pointer[4];
};

Node* curr;
Node* root;
Node* right;
Node* newRoot;
bool nullRoot = true;

public:
void insert(string data);
void initNode(Node* node);
};

#endif

它总是在第 19 行因内存地址错误而中断。我试过调试它,它在字符串文件中的第 2245 行中断(如果有帮助的话)。这些信息并没有真正帮助我,所以也许有人可以帮助我解决这里到底出了什么问题?

最佳答案

存在多个问题。修复以下内容,然后看看它是否有效...

cpp,插入:
您的 if 条件是一项任务。

cpp,初始化节点:
该函数正在更改传递的指针的拷贝。
调用者不会得到分配对象的任何东西。
使用对指针的引用 (&*) 或指向指针的指针
(具有匹配的函数调用和内容)作为参数..即,

void tree234::initNode(Node *& node)

关于c++ - 插入到 2-3-4 树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21741898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com