2

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.

0

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

8 Comments

doesnt the .count() be very slow as it counts them all? And why is using macros bad?
I like the fact that you explained every solution. Great effort Mr.GMan.
@Newbie: Where do you get the notion it counts them all? For map, count will literally just do: return find(key) != end();.
"count", i guess its misleading function name then :P
Btw, why is using macro bad in my case? doesnt templates make bigger executables?
|
1

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.

9 Comments

Does it insert a new empty element every time the key didnt exist? So the memory use can go higher ang higher?
@Newbie: No, because it only makes it if it's not there. After the first time, it'll return the existing element.
But if i check million random strings, it will create million random elements into the map and set their values to zero because they didnt exist?
@Newbie: Right. The operator[] is: "get element and return it". It isn't for checking if an element is there.
So, to leave no doubts, the operator[] will be slower than my first example?
|
0
if(SomeMap["something"] != NULL){
    // key exists
}

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

1 Comment

NULL is 0. If there are valid elements that compare to 0 then this is broken.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.