如何使用malloc分配映射键

How to allocate map key using malloc?

本文关键字:映射 分配 malloc 何使用      更新时间:2023-10-16

如果我尝试下面的代码,它将地址存储为键而不是值,因此"同一键存储两次"

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*键,否则无论如何都会得到意想不到的结果。