我地图上的记忆问题在哪里?

Where is the memory issue in my map?

本文关键字:问题 在哪里 记忆 地图      更新时间:2023-10-16

我正在从数据库加载数据并将其插入到地图中。当我尝试打印地图大小和数据时,它仍然显示大小为1,并且只打印最后一行。所有以前的数据将被覆盖并包含最后一个值。这里的任何指针问题。由于公司的问题,我更改了变量名。

我也做了一些检查点。所有键值都是唯一的

typdef long_char char[38];
for(int j = 0; j < 31; j++)
{
    sample_enum param_sub_type = result_set[j];
    long_char param_name;
    strncpy(param_name,result_set[j], sizeof(param_name));
    input_status_cd.insert(std::pair<long_char,sample_enum>(param_name, param_sub_type));      
    /*Insert Into Map */    <I suspect this may be issue but not sure>
}
/*Printing Size of map */
input_status_sd::size_type input_status_cd_size;
etlog_msg(intput_status_cd_size :] [%d]",intput_status_cd.size());

这是因为long_char被定义为char[38],所以当您插入到映射中时,它将尝试使用operator<,这将导致比较数组的第一个字符的地址。由于您是在循环中创建这个数组,因此很可能会分配相同的堆栈帧,因此每个对象的第一个字符的地址保持不变。因此,当map认为您再次插入相同的对象时,所有先前的数据都会被覆盖。解决这个问题最简单的方法是使用std::string作为long_char的类型定义。

您应该使用std::map<std::string,sample_enum>而不是std::map<long_char,sample_enum>。这样,std::stringoperator<将按预期工作(按字典顺序比较)。对于std::string,你不能使用strncmp来复制字符串,因为你必须使用赋值操作符。