B
Bob Altman
Hi all,
I use an STL map to store integers associated with string keys, like this:
map<string, int> g_myMap;
void Init() {
myMap["a"] = 0;
myMap["b"] = 1;
}
int Get(string key) {
if (myMap.count[key] == 0) return -1;
return 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 myMap that the default value
is -1 rather than 0. That way I could rewrite Get as:
int Get(string key) {
int result = myMap[key];
if (result == -1) <delete 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
I use an STL map to store integers associated with string keys, like this:
map<string, int> g_myMap;
void Init() {
myMap["a"] = 0;
myMap["b"] = 1;
}
int Get(string key) {
if (myMap.count[key] == 0) return -1;
return 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 myMap that the default value
is -1 rather than 0. That way I could rewrite Get as:
int Get(string key) {
int result = myMap[key];
if (result == -1) <delete 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