B
Bob Altman
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
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