Newbie
Newbie

Reputation: 1613

Which method to use to check if array key exists in std::map?

I'm using the following code in some cases:

#define array_key_exists(find_key, arr) (arr.find(find_key) != arr.end())

But i also use simply this method:

if(SomeMap["something"]){
    // key exists
}

I am using String to int map.

Are they both as fast...? Or is there a possibility for errors with the second case, assuming i am not using zero value in the map values at all? So far the second case seems to work just fine.

Upvotes: 2

Views: 6662

Answers (3)

Bob
Bob

Reputation: 11

if(SomeMap["something"] != NULL){
    // key exists
}

Assuming that you do not add any NULL items to the map

Upvotes: 0

GManNickG
GManNickG

Reputation: 504333

The second if-statement will always be entered, because if the key doesn't exist it will be created. (After which, subsequent calls will just return the existing element.)

If you want to find a value and use it if it exists, you typically do this:

std::map<T>::iterator iter = theMap.find(theKey);
if (iter != theMap.end())
{
    // use iter
}
else
{
    // value doesn't exist
}

If you simply want to know if it's in there, without using it, do:

if (theMap.count(theKey)) // in map, count will return either 0 or 1
{
    // it exists
}
else
{
    // it doesn't exist
}

At the very least, don't use a macro! There's no reason to in C++:

template <typename Map, typename Key>
bool contains(const Map& pMap, const Key& pKey)
{
    return pMap.find(pKey) != pMap.end();
}

But there's no use for this, just use count.

Upvotes: 12

Peter G.
Peter G.

Reputation: 15144

Use find and compare against end iterator like the first method. The second method will insert an empty element into the map if the key didn't exist.

Upvotes: 1

Related Questions