开发者

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["somet开发者_StackOverflowhing"]){
    // 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.


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.


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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜