I'm working with LLVM, and I'm having issues with the following piece of code that I did not write:
static std::map<std::string, Value*> NamedValues;
... //Lots of other code
Value *V = NamedValues["Demo string"];
return V ? V : ErrorV("V is not in NamedValues map.");
From what I understand of std::map, it should never return a null pointer (Unless it's out of memory?), so I have a hard time understanding how V being 0 would indicate that V is not in the map. As is, my program is always getting an error here, but I can't figure out why. Any help on what is going on here?
std::map::operator []
returns a reference to the value if the key already exists, if the key does not exist, it inserts the key along with default-constructed value, and returns a reference to that value.
POD types (like pointers) have zero-initialization upon default construction. meaning that the pointer will have nullptr
value if its default constructed.
if the key "Demo string"
did not exist before calling NamedValues["Demo string"];
, the map will create a default constructed pointer as value, which will be constructed as nullptr
.
if you want to find out if the map contains a key, you need to use find
+ end
:
if (map.find(yourKey) != map.end()){
//the key exists
}
EDIT:
as @ShadowRanger has pointed out, count
can be used as well.
if (map.count(yourKey)){
//the key exists
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With