C++ map::find char * vs. char []
c++, dictionary, std
Solution
Pointer comparison, not string comparison, will be performed by `map` to locate elements. The first two work because `"test"` is a string literal and will have the same address. The last does not work because `buf` will not have the same address as `"test"`.
To fix, either use a `std::string` or define a comparator for `char*`.
Problem
I'm using C++ map to implemented a dictionary in my program. My function gets a structure as an argument and should return the associated value based on `structure.name` member which is `char named[32]`. The following code demonstrates my problem: ``` map <const char *, const char *> myMap; myMap.insert(pair<const char *, const char *>("test", "myTest")); char *p = "test"; char buf[5] = {'\0'}; strcpy(buf, "test"); cout << myMap.find(p)->second << endl; // WORKS cout << myMap.find("test")->second << endl; // WORKS cout << myMap.find(buf)->second << endl; // DOES NOT WORK ``` I am not sure why the third case doesn't work and what should I do to make it work. I debugged the above code to watch the values passed and I still cannot figure the problem. Thanks!