使用指针作为C 中映射的值
Using pointers as values for map in C++
我有一个 map<key_t, struct tr_n_t*> nodeTable
,我正在尝试执行 nodeTable[a] = someNode
,其中 a
属于类型 typedef long key_t
,而 someNode
是类型o_t*
。
我在stl_function的执行中以下几点得到分段故障。h:
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
源代码:
#include <stdio.h>
#include <stdlib.h>
#include <map>
using namespace std;
typedef long key_t;
typedef struct tr_n_t {
key_t key;
map<key_t, struct tr_n_t *> nodeTable;
} o_t;
int main() {
o_t *o = (o_t *) malloc(sizeof(o_t));
o->nodeTable[1] = o;
return 0;
}
我不是使用地图吗?
问题是因为您使用malloc初始化o,因此分配了它的内存,但未调用其构造函数。
将其更改为o_t *o = new o_t();
,因为使用new
代替malloc
会调用地图的构造函数。
您正在为o_t
分配空间,但是您没有初始化内存。改用此方法:
#include <map>
typedef long key_t;
struct o_t {
key_t key;
std::map<key_t, o_t*> nodeTable;
};
int main() {
o_t o;
o.nodeTable[1] = &o;
return 0;
}
您正在使用C样式malloc
来分配包含C 类的结构。std::map
的构造函数没有称为,因此对象无效。您不能将malloc与普通结构一起使用,而不能在需要正确初始化才能正常工作的对象上使用。
尝试将分配更改为
o_t *o = new o_t();
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- 智能指针作为无序映射键,并通过引用进行比较
- C++:映射结构中的结构指针
- 如何创建对象函数指针C++映射?
- 整数键映射到头文件中的成员函数指针
- C++在一个映射中存储不同的指针类型(并处理销毁)
- 添加要映射的对象的唯一指针
- 通过指针或引用将映射传递给函数?
- 在映射中存储模板类函数指针
- c++:复制、删除和运算符=在原始指针映射中
- 将唯一指针插入std::映射
- 在循环(C++)中用新指针填充映射
- C++:如何初始化包含具有给定键的指针列表的映射
- 如何将带指针的结构插入到映射中
- 重构MFC消息映射以包括完全限定的成员函数指针
- C 正确的方法来初始化和处理映射指针
- 定义基于模板的映射指针,以便在验证范围时将 int 解析为枚举
- C++中的静态无序映射指针初始化
- 动态分配映射指针值
- 如何在c++中维护映射指针的向量