我想知到申请的TrieNode数组的第index个位置是否为空,为空就创建结点,但是现在这样比较会报错,求说一下


#include <iostream>
#include <vector>
#include <string.h>
using namespace std;

class TrieNode;
class TrieNode
{
    public:
        int pass;
        int end;
        TrieNode* nexts;
        TrieNode()
        {
            pass=0;
            end=0;
            nexts=(TrieNode*)calloc(sizeof(TrieNode),26);
            }
};
class Trie
{
    public:
    TrieNode root;
    Trie()
    {
        root=*(new TrieNode);
    }
    void insert(string str)
    {
        if(str.size()==0)
        {
            return;
        } 
        TrieNode node=root;
        node.pass++;
        int index=0;
        for(int i = 0;i < str.size();i++) 
        {
            index=str[i]-'a';
            if(node.nexts[index]!=NULL)
            {
                
            }
            
        }
        
    }
};
int main(int argc, char** argv){
    string a ="abc";
    Trie t ;
  t.insert(a);
    return 0;
  }

以下答案引用自GPT-3大模型,请合理使用:

// 首先,你可以先在建立TrieNode时,将nexts改为vector<TrieNode*>
// 然后,改写你的insert函数,代码可以参考如下:

void insert(string str) {
    if (str.size() == 0)
        return;
    TrieNode node = root;
    node.pass++;
    int index = 0;
    for (int i = 0; i < str.size(); i++) {
        index = str[i] - 'a';
        if (node.nexts.size() <= index || node.nexts[index] == NULL) {    // 判断当前的位置是否为空,若为空则新建结点
            node.nexts[index] = new TrieNode();
        }
        node = node.nexts[index];
        node.pass++;
    }
    node.end++;
}

如果我的回答解决了您的问题,请采纳我的回答