Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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?

like image 721
Muhammad Yusuf Avatar asked Sep 16 '25 00:09

Muhammad Yusuf


1 Answers

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;
}
like image 191
Jarod42 Avatar answered Sep 18 '25 14:09

Jarod42