c++ - 添加元素 <string, pointer> 以 boost 无序 HashMap

标签 c++ boost

我在 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/

相关文章:

来自指针回溯的 C++ 段错误

c++ - boost::split 与 boost::iter_split 之间的区别

c++ - 围绕 const char* 和长度的轻量级容器,无需复制数据

c++ - 如何在进程运行时捕获标准输出并打印到控制台和文件 (C++/Boost.Process)

c++ - 用于 boost::test 的带有海龟模拟的模拟对象

c++ - 为什么编译器提示不能用 Base 类型的右值初始化 "Derived"

c++ - 搜索具有上限和下限的 map

c++ - 在 char 字符串数组上应用 c++ "lower_bound"

c++ - 在每个分号后有一个带有反斜杠的 c++ 代码块是什么意思?

c++ - 使用 boost QT 和 mingw 的多线程