使用指针作为C 中映射的值

Using pointers as values for map in C++

本文关键字:映射 指针      更新时间:2023-10-16

我有一个 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();