Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 << '
';
}
else 
{
    std::cout << "Not found
";
}  

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
670 views
Welcome To Ask or Share your Answers For Others

1 Answer

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::strings 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...