# How to tell if a map element exists?

## Recommended Posts

Mizipzor    247
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 on other sites
JY    289
map::find

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

##### Share on other sites
Mizipzor    247
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 on other sites
Zahlman    1682
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 :/