Jump to content
  • Advertisement
Sign in to follow this  
Mizipzor

How to tell if a map element exists?

This topic is 4858 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi there, my texture name (string) are represented by chars so I can use them in chararrays as tilemaps. It looks like this:
std::map <char, std::string> BmpRef; // so we know which string(texture) is represented by which char
Then we got the function to retrieve which string is tied to which char:
std::string FindBmpRef(char a) {return BmpRef[a];}; // find which string is represented by the specified char
But what about if the char (a) doesnt exists in the map? Then I want to return the string "UNDEFINED". How do I check for a map element? Couldnt find it in the msdn...

Share this post


Link to post
Share on other sites
Advertisement
map::find

returns an iterator with the passed in key. if it doesn't exist returns equivalent to end()

Share this post


Link to post
Share on other sites
Thanks, I wrote the function like this:

std::string Sdl_handle::FindBmpRef(char a) {
if( BmpRef.find(a) == BmpRef.end() ) {
return "UNDEFINED";
}
else
return BmpRef[a];
}


Does it look ok to you?

Share this post


Link to post
Share on other sites
In case you are wondering, if the key is not present, the [] operator will return a default-constructed value - and also insert that key-value pair (with the new key and the default value). For std::string, that would mean a default of an empty string (zero-length). Which is easy enough to check for, but the extra insertions are undesirable :/

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!