gpt4 book ai didi

c++ - 在 C++ 中使用指针作为映射的值

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:08 24 4
gpt4 key购买 nike

我有一个 map<key_t, struct tr_n_t*> nodeTable我正在尝试执行 nodeTable[a] = someNode其中 a类型为 typedef long key_tsomeNode类型为 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;
}

我没有正确使用 map 吗?

最佳答案

问题是因为你使用 malloc 初始化 o,它的内存被分配但它的构造函数没有被调用。

将其更改为 o_t *o = new o_t();因为使用 new而不是 malloc将调用 map 的构造函数。

关于c++ - 在 C++ 中使用指针作为映射的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13321434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com