问题
I have a map declared like this:
std::map<const char*, const char*> map2D;
The map is filled by the output from an API function, which returns const char*
:
map2D.insert(std::pair<const char*, const char*>(TempA, TempB));
Now there are 50 TempA
values and 50 TempB
values, and there is one key with the name of "months". When I am searching for this key, I am getting "not found". E.g.:
std::map<const char*, const char*>::iterator it;
it = map2D.find("months");
if (it != map2D.end())
{
std::cout << "Found " << it->first << " " << it->second << '\n';
}
else
{
std::cout << "Not found\n";
}
But when I am doing it like this:
map2D.insert(std::pair<const char*, const char*>("months", "June");
I can find the respective month. After searching the web, I understand that this problem may be related to the use of const char*
. Can anyone further clarify this?
回答1:
Comparing two const char*
for equality does not do what you think it does; it compares pointer values, not the strings that the pointers point to. With string literals this may occasionally "work", but you have no way of knowing that two string literals even with the same characters in it will be stored at the same address. You would have to provide a custom comparator that invokes strcmp
, in order to make that work reliably.
You're much better off with a std::map<std::string, std::string>
. It doesn't matter that your third-party API gives you const char*
: you can simply construct std::string
s from those.
This container will have elements with clear ownership and lifetime semantics, and be automatically ordered properly. In short, all your problems will simply go away.
If you still really need to store const char*
, be aware that such a requirement is exceedingly rare and should only be even fleetingly considered if you are prepared to litter your code with explanatory comments detailing precisely how and why your container is safe; hint: it almost certainly is not.
来源:https://stackoverflow.com/questions/24398824/error-trying-to-find-const-char-key-from-stdmap