I use an STL map to store integers associated with string keys, like this:
map<string, int> g_myMap;
void Init() {
g_myMap["a"] = 0;
g_myMap["b"] = 1;
}
int Get(string key) {
if (g_myMap.count[key] == 0) return -1;
return g_myMap[key];
}
So, the idea is that I return -1 if the specified key isn't in the map;
otherwise I return the int associated with the key.
Here's my question: The caller almost always gives me a valid key, so
calling the count function to detect an invalid key is really inefficient.
Is there a more efficient way to catch the unusual case where the user calls
Get with a bogus key?
One thing I thought of is to somehow convince g_myMap that the default value
is -1 rather than 0. That way I could rewrite Get as:
int Get(string key) {
int result = g_myMap[key];
if (result == -1) <delete g_myMap[key]>
return result;
}
This would work but I don't know how to change the map so that it creates a
value of -1 rather than 0 if the key doesn't exist.
TIA - Bob
Cholo Lennon - 30 Jan 2008 02:54 GMT
Try using map::find to locate the integer value. find returns map::end() in
case of failure. Remember that map is an ordered container, so using find is
really fast and efficient.
Regards
--
Cholo Lennon
Bs.As.
ARG
>I use an STL map to store integers associated with string keys, like this:
>
[quoted text clipped - 34 lines]
>
> TIA - Bob
Brian Muth - 30 Jan 2008 04:33 GMT
In addition to Chloe's response, find gives you the iterator to the key-value pair. If it does not equal g_myMap.end() you can
return (iterator)->second();
Brian
Bob Altman - 30 Jan 2008 23:56 GMT
Thanks Chloe and Brian, that's just what I was looking for!
- Bob
> In addition to Chloe's response, find gives you the iterator to the
> key-value pair. If it does not equal g_myMap.end() you can return
> (iterator)->second();
>
> Brian