我在C ++中使用boost无序hashmap,我无法在哈希映射中添加元素(我的程序有分段错误)。我是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);
问题出在最后一行。
答案 0 :(得分:3)
停止使用malloc
。那是C.正确的语法是:
OuterRelation *outer_relation = new OuterRelation;
您对malloc
的使用已经为OuterRelation结构分配了足够的空间。如果结构只包含普通旧数据,这可能就足够了。但是,hash_table
成员是一个类,并使用malloc
使其未初始化。
new
(最基本的)是malloc
和对new
'd对象的构造函数的调用的组合。结构的构造函数将依次调用其成员的构造函数,包括map。地图的构造函数将初始化其数据成员。
您还需要停止使用new
作为变量名称。这与new
C ++关键字冲突。