-1

If I try the code below, it stores the address as a key and not the value, therefore "the same key is stored twice"

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;
    }

printed result:

size: 2
hhhhh | 85
hhhhh | 85
15412s
  • 3,298
  • 5
  • 28
  • 38

1 Answers1

2

You don't. Use std::string as a key instead.

Unless you are providing an appropriate comparator functor to handleconst char* keys properly, you will get unexpected results anyways.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • one of the classes in the code is printing the map values on its destructor, but with std::string seems like the value was destroyed and I'm getting core dump – 15412s Jun 27 '16 at 16:10
  • 1
    @15412s Well, that's a different question, and most probably not related to using `std::string` as key, but some wrong logic in a different part of your program. – πάντα ῥεῖ Jun 27 '16 at 16:12