Reputation: 397
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
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