【问题标题】:How can I use arrays of map which nested in arrays of structure?如何使用嵌套在结构数组中的地图数组?
【发布时间】:2022-01-14 06:50:22
【问题描述】:

我有以下代码用于创建包含地图数组的结构数组。我的问题是如何向地图添加新值?以及如何将值更新为退出键?

struct Line {
        map<int, vector<float>> *con_inf;
        float *points_x; // Array
        float *points_y; // Array
        int points_num;
    };
void update_map(int points_length) {
    struct Line *line_struct = NULL;
    line_struct = (struct Line *)malloc(sizeof(int) *points_length);
    for (int line_struct_idx = 0; line_struct_idx < points_length; line_struct_idx++) {
        line_struct[line_struct_idx].con_inf = (map<int, vector<float>> *) malloc(sizeof(int) *points_num);
        line_struct[line_struct_idx].points_x = (float *) malloc(sizeof(int) *points_num);
        line_struct[line_struct_idx].points_y = (float *) malloc(sizeof(int) *points_num);
        line_struct[line_struct_idx].points_num = points_num;
    }
}

我使用下面的代码来确认密钥退出。不存在则为真

if (line_struct[cur_line_idx].con_inf[cur_point_idx].count(con_line_idx) == 0) {
    // add value
} else {
    // update value
}

但有时它不起作用。一些明显不存在的东西会得到 False 结果(意味着existint)。当代码要更新值时,我会得到Segmentation fault(core dumped)。

【问题讨论】:

  • 已知变量,如 'points_length' 'points_num' 'cur_line_idx' 'cur_point_idx' 'con_line_idx'
  • 请提供一个minimal reproducible example,它演示了定义一个填充你的结构和一个“工作”的案例和一个“失败”的案例。

标签: c++ arrays dictionary structure


【解决方案1】:

line_struct = (struct Line *)malloc(sizeof(int) *points_length);

这显然是错误的。您正在分配 Line 结构的数组,但出于某种原因使用 sizeof(int) 而不是 sizeof(Line)。使用这样的数组是一个明显的未定义行为,所以难怪你会遇到段错误。

首先,最好避免使用std::vector 来代替对数组使用直接内存分配。

Secondary malloc 只是内存分配。使用它来创建动态对象(如std::map)是一个非常糟糕的主意(UB 也是如此) - 不会运行任何构造函数,因此结果对象将处于不确定状态。如果您确实必须手动管理内存,请使用new/delete 运算符,甚至更好 - 智能指针std::unique_ptr/std::shared_ptr

【讨论】:

  • 我之前用过'std::vector',但是创建数组的时间太长,因为长度太大了,也会造成内存溢出。
  • 当我使用'new/delete'手动管理内存而不是使用'malloc'时,代码可以正常运行!
猜你喜欢
  • 2015-08-14
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 2020-08-23
相关资源
最近更新 更多