我在 C++ 中使用 boost unordered hashmap,但我无法将元素添加到我的 hash map(我的程序有段错误)。我是 C++ 的新手,我的大部分代码( HashMap 处理除外)都是 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
。那是针对 C 的。正确的语法是:
OuterRelation *outer_relation = new OuterRelation;
您对 malloc
的使用已经为 OuterRelation 结构单独分配了足够的空间。如果结构只包含普通旧数据,这可能就足够了。但是,hash_table
成员是一个类,使用 malloc
使其未初始化。
new
是(最基本的)malloc
和对 new
对象的构造函数的调用的组合。您的结构的构造函数将依次调用其成员的构造函数,包括映射。 map 的构造函数将初始化其数据成员。
您还需要停止使用 new
作为变量名。这与 new
C++ 关键字冲突。
关于c++ - 添加元素 <string, pointer> 以 boost 无序 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22200870/