Kavfixnel
Kavfixnel

Reputation: 331

C++ map to use string value as key

I want to use the c++ standard map to map from a string key to another object (integer in example), but it seems as though c++ uses the pointer as the key, rather than the value of the char*:

#include <iostream>
#include <map>
#include <string.h>

using namespace std;

int main()
{
    std::map<char *, int> m;

    const char *j = "key";
    m.insert(std::make_pair((char *)j, 5));

    char *l = (char *)malloc(strlen(j));
    strcpy(l, j);

    printf("%s\n", "key");
    printf("%s\n", j);
    printf("%s\n", l);

    // Check if key in map -> 0 if it is, 1 if it's not
    printf("%d\n", m.find((char *)"key") == m.end());
    printf("%d\n", m.find((char *)j) == m.end());
    printf("%d\n", m.find((char *)l) == m.end());
}

Output:

key
key
key
0
0
1

Is there any way that I can make the key of the map the "value"/content of the key, similar to other languages like JavaScript?

Upvotes: 1

Views: 9450

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73364

In C++ you really want to use std::string to represent a character-string, rather than doing strings the old/C-style char * way. Here's what your program looks like when done using std::string:

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
    std::map<string, int> m;

    const char *j = "key";
    m.insert(std::make_pair(j, 5));

    std::string l = j;

    printf("%s\n", "key");
    printf("%s\n", j);
    printf("%s\n", l.c_str());

    // Check if key in map -> 0 if it is, 1 if it's not
    printf("%d\n", m.find("key") == m.end());
    printf("%d\n", m.find(j) == m.end());
    printf("%d\n", m.find(l) == m.end());
}

Upvotes: 4

Related Questions