我想创建一个树状结构,但基于主题的unordered_map
。简而言之,我想创建一个主题树,并且想到了这种方法:
typedef struct topic_tree {
int id;
unordered_map<string, struct topic_tree *> children;
} topic_tree;
这听起来是个不错的主意,因为对于每个“主题”,我都会有一个ID(或我需要的任何东西),并且每个节点上都有一个从下一个字符串到下一个topic_tree的映射,因此上。
我尝试创建此树:first/second/third
。这意味着第一个是第二个的父级,第二个是第三个的父级。可能还有其他一些内容,例如first/forth/fifty
这意味着现在第一个有两个孩子,第二个和第四个。这就是解释。现在让我们解决问题:
例如,我要声明这一点:
topic_tree *root = (topic_tree *)malloc(sizeof(struct topic_tree));
root->id = -1;
topic_tree *x = (topic_tree *)malloc(sizeof(struct topic_tree));
x->id = 5;
root->children["first"]=x;
但是:root->children["first"] = x;
给了我一个Floating point exception
,但我不知道为什么。
原因是因为在分配了topic_tree
结构后,您并未对其进行初始化。因此,std::unordered_map
正在未初始化的内存上工作。
通常,在c ++应用程序中,应避免使用malloc,而应使用new
。像这样分配节点时:new topic_tree{}
你应该没事的。
如果要坚持使用malloc,则必须显式调用构造函数。可以这样完成:
new (root) topic_tree{};
但是要注意free
,您需要调用析构函数!
root->~topic_tree();