添加元素<字符串、指针>以提升无序哈希图

Adding an element <string, pointer> to boost unordered hashmap

本文关键字:无序 哈希图 gt 元素 lt 字符串 添加 指针      更新时间:2023-10-16

我在C++中使用了boost无序哈希图,但我无法将元素添加到我的哈希图中(我的程序有分段错误)。我对C++很陌生,我的大部分代码(哈希映射处理除外)都是 C 代码。你能指出问题吗?

// my simplified code
struct Record
{
        char *data;
};
typedef boost::unordered_map<std::string, std::vector<Record*> > MAP;
typedef std::pair<std::string,std::vector<Record*> > PAIR;
struct OuterRelation
{
        short num_keys;
        short join_key_ndx;
        MAP hash_table;
};
OuterRelation *outer_relation = (OuterRelation *) malloc (sizeof(OuterRelation)) ;
Record *new = (Record *) malloc(sizeof(Record));
new->data = "somestring";
outer_relation->hash_table[new->data].push_back(new);

问题出在最后一行。

停止使用 malloc 。正确的语法是:

OuterRelation *outer_relation = new OuterRelation;

您对malloc的使用已经为外部关系结构单独分配了足够的空间。如果结构仅包含普通旧数据,这可能就足够了。但是,hash_table 成员是一个类,使用 malloc 使其未初始化。

new(最基本的)是malloc和对new 'd 对象的构造函数的调用的组合。结构的构造函数将依次调用其成员的构造函数,包括映射。映射的构造函数将初始化其数据成员。

您还需要停止使用 new 作为变量名称。这与new C++关键字冲突。