Muhammad Yusuf
Muhammad Yusuf

Reputation: 397

In C++ map, which is better for usage/perfomance and conforms to the guidelines, using find_if or find then and .at

I am using a C++ map, in which I need to search for an element then get the element if it is exist.

The first way to do that is using find

if (mymap.find(mykey) == mymap.end()) 
{
    //return error code
    return ERROR_CODE;
}
else
{
    value = mymap.at(mykey).second;
    return SUCCESS_CODE;
}

second way to do that:

auto iter= find_if(mymap.begin(), mymap.end(), [&key](auto &item){return item.first == key;})
if(iter == mymap.end())
{
   return ERROR_CODE;
}
else
{
    value = iter->second;
    return SUCCESS_CODE;
}

Is there any technical consideration or guidelines (like cpp guideline) that mention something like that, which way is better?

Upvotes: 4

Views: 707

Answers (1)

Jarod42
Jarod42

Reputation: 218323

You should not use std::find_if which is linear, whereas you might have iterator in logarithm time. You might do

auto it = mymap.find(mykey)
if (it == mymap.end()) 
{
    //return error code
    return ERROR_CODE;
}
else
{
    value = it->second;
    return SUCCESS_CODE;
}

Upvotes: 9

Related Questions