如何使用malloc分配映射键
How to allocate map key using malloc?
如果我尝试下面的代码,它将地址存储为键而不是值,因此"同一键存储两次"
static map<const char *, int> lMap;
const char * msg = "hhhhh";
char *buf = (char *) malloc(6);
strcpy(buf, msg);
lMap.insert(make_pair(buf, 85));
buf = (char *) calloc(5, sizeof (char));
strcpy(buf, msg);
lMap.insert(make_pair(msg, 85));
cout << "size: " << lMap.size() << endl;
map<const char *, int>::const_iterator it2;
for (it2 = lMap.begin(); it2 != lMap.end(); ++it2) {
cout << it2->first << " | " << it2->second << endl;
}
打印结果:
size: 2
hhhhh | 85
hhhhh | 85
你没有。使用std::string
作为密钥。
除非提供适当的比较器函子来正确处理const char*
键,否则无论如何都会得到意想不到的结果。
相关文章:
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- C++ 将元素分配给映射值时访问错误
- 包含动态分配内存作为值的映射的取消定位速度有多快?
- 如果可能,标准::映射分配是否静态
- 如何在 OpenCL 中使用缓冲区分配和映射内存机制
- 我如何正确地为std ::映射分配内存
- 我如何将输入分配给在 for 循环中设置的映射功能
- 映射和设置总是一次分配一个项目吗
- 静态映射中动态分配的对象.删除必要的
- C++:通过从映射向量分配映射实例来填充映射的映射
- 映射中的分配最终为0
- C 索引中的字符串映射而无需分配
- 循环访问映射并删除动态分配的元素
- 将无序映射与动态分配的用户定义类一起使用
- STL映射是如何分配的?堆叠或堆
- 任何查找分配给映射的内存大小的方法
- 两个映射之间的分配-移动语义和性能
- c++动态分配(像素映射)
- 标准::移动和映射分配
- C++ std::映射分配错误:无法在赋值中将' type **'转换为'type *'