如何使用malloc分配map密钥?

时间:2016-06-27 16:04:11

标签: c++ pointers malloc stdmap

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

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

1 个答案:

答案 0 :(得分:2)

你没有。请改用std::string作为密钥。

除非您提供适当的比较器函数来正确处理const char*个键,否则无论如何都会得到意想不到的结果。