在 stl 映射中插入新项目时,将覆盖到第一个元素
When insert a new item in stl map, occurs an overwrite to first element
首先,我有以下代码:
map<char*, char*> records;
// id, value are buffer variables to store the text that returns from `strcpy()`
char *id = (char*)malloc(sizeof(char*) * 20);
char *value = (char*)malloc(sizeof(char*) * 20);
sql->open(dbFile);
sql->query("SELECT * FROM categories");
while(sql->fetch() != SQLITE_DONE){
// copy the text that returns from `sql->getValue`, then convert that text from `const unsigned char*` to `const char*`
strcpy(id, reinterpret_cast<const char*>(sql->getValue(0)));
strcpy(value, reinterpret_cast<const char*>(sql->getValue(1)));
// insert the values that in `id`,`value` as new item
records.insert(pair<char*, char*>(id, value));
}
free(id);
free(value);
前面代码的思想是使用 strcopy()
复制返回此方法sql->getValue(0)
的文本,然后将该文本从 const unsigned char*
转换为 const char*
,然后将这些文本存储在id
中,value
变量,然后插入id
、value
作为新项。前面的步骤发生在从数据库获取的每个数据上。
进一步澄清这个想法:
例如,从数据库中获取了三行(fruits
、vegetables
、sweets
)。
当然,当将这三个数据插入地图容器时,容器中的项目数将是三个项目第一(fruits
),第二(vegetables
),第三(sweets
)。
就我而言,在检查项目数量时,我发现只有一个项目,并且该项目sweets
。
现在,我很惊讶,其余的物品在哪里?
您正在覆盖相同的内存板三次,并将指向这些板的指针存储三次。就地图而言,它每次都是相同的值,因为指针永远不会改变。
看来你真正想要的是有一个字符串映射,而不是指针。如果您使用 std::string
,这将容易得多:
#include <string>
...
map<string, string> records;
string id, value; // size of allocation will be handled by the string class.
sql->open(dbFile);
sql->query("SELECT * FROM categories");
while(sql->fetch() != SQLITE_DONE){
// string has an assignment operator from C-style strings
id = reinterpret_cast<const char*>(sql->getValue(0));
value = reinterpret_cast<const char*>(sql->getValue(1));
// more readable way of writing the insert. id, value will be copied into
// the map.
records[id] = value;
}
// freeing unnecessary; string class handles it when id, value go out of scope.
这也具有使代码异常安全(至少是字符串)而没有try-catch-block的优点。std::string
的析构函数将处理清理,而不管范围如何离开。
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 将参数初始化为构造函数,而不是第一个
- 无法在硬件模式下创建 SGX 安全区 - "invalid launch token"即使文档将无效的启动令牌指定为第一个