STL map initialization (again - corrected example syntax)

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
 
C

Cholo Lennon

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
 
B

Brian Muth

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top