初始化映射的值,该映射是结构内的字段
initializing value of a map which is a field inside a structure?
当我尝试向我的地图(命名为子(插入值时,它会出现分割错误。我无法理解我的方法(评论和非评论(到底是什么问题。
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,则可以依赖它。
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- C++匿名结构作为std::映射值
- 添加静态constexpr成员是否会更改结构/类的内存映射
- C++:映射结构中的结构指针
- 无法添加多个键以映射将结构作为键
- 如何在 c++ 中创建结构向量的映射
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 在映射中使用结构作为键,忽略 == 运算符,误报
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- 使用结构和映射创建priority_queue
- 在无序映射的结构化绑定中推导类型
- 如何将带指针的结构插入到映射中
- C++调用存储在映射结构中的函数指针
- 映射结构也支持排序
- 它无法将 c++ 映射结构编译为 map<A、pair<B、C> >
- 非易失性C++映射结构的备份方案
- 内存映射文件-映射结构而不是文件
- 无法推送到由静态映射<结构创建的队列,队列>
- 将映射结构强制转换为void指针和解引用