将相同的密钥(使用 malloc 创建)添加两次以映射

Same key(created with malloc) is added twice to map

同一个key怎么可能在map中被添加两次? 如果值被更改,它不应该覆盖该值吗?

static map<const char *, int> lMap;
    const char * msg = "hhhhh";

    char *buf = (char *) malloc(5);
    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

您在地图中没有两次使用相同的键。地图的关键是 char * (即指针)。您有两个不同的指针值恰好指向相同的字符串。

const char* 是一个指针。用 < 比较两个指针就是比较它们指向的地址。默认情况下,std::map 使用 < 来比较键。这意味着两个不同的 const char* 对象是不同的键,即使它们在被解释为以 nul 结尾的字符串时恰好包含相同的数据。

您正在编写 C++,而不是 C。如果您想要一个字符串,请使用 std::string,而不是指向希望以 nul 结尾的缓冲区的指针。

     static map<const char *, int> lMap;

以上语句将 int 映射到 const char* 而不是 intvalue pointed by const char*

地图不关心键指向什么,它只关心有两个不同的键,因此有两个条目。