初始化映射的值,该映射是结构内的字段

initializing value of a map which is a field inside a structure?

本文关键字:映射 结构 字段 初始化      更新时间:2023-10-16

当我尝试向我的地图(命名为子(插入值时,它会出现分割错误。我无法理解我的方法(评论和非评论(到底是什么问题。

struct trienode{
    map < char , struct trienode* > child;
    bool eow;
}; typedef struct trienode trienode;
void insert_trie(trienode* root,string mystr){
    int len = mystr.length();
    int p=0;
    char ch=mystr.at(p);
    trienode* temp=root;
    while(p<len){
        map<char, trienode* >::iterator itr=(temp->child).find(ch);
        if( itr!=(temp->child).end()){
            temp=itr->second;
            p++;
            ch=mystr.at(p);
        }
        else{
            trienode* temp2;
            temp2=(trienode*)malloc(sizeof(trienode));
            temp->child.insert(make_pair(ch,temp2));//segmentation fault occure on this line or line below it.
            //(temp->child)[ch]=temp2;
            if(p==len-1){
                temp2->eow=true;
            }
            else{
                temp2->eow= false;
                temp=temp2;
            }
            p++;
            ch=mystr.at(p);
        }
    }
}

您需要使用 new ,而不是 malloc 。 否则std::map将不会初始化。 段错误可能发生在std::map的复制构造函数内部。


  • 您可以使用std::map<char,trienode>进行child并避免所有这些错误。

  • std::map::operator[]为您插入项目,如果您确保trienode::eow初始化为 false,则可以依赖它。