Sign in to follow this  
Mizipzor

How to tell if a map element exists?

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this