How to tell if a map element exists?

Started by
2 comments, last by Zahlman 18 years, 9 months ago
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...
Advertisement
map::find

returns an iterator with the passed in key. if it doesn't exist returns equivalent to end()
"Absorb what is useful, reject what is useless, and add what is specifically your own." - Lee Jun Fan
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?
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 :/

This topic is closed to new replies.

Advertisement