Home:ALL Converter>Understanding std::map::find

Understanding std::map::find

Ask Time:2017-07-05T03:04:50         Author:Ashutosh

Json Formatter

I am trying to learn how to use std::map with functions. I am a bit confused about how std::map::find works in this regard. Here is a simple code where I use a Lambda function along with map.

auto Lambda = [](const int&a, const int& b) {
 cout << "\n Inside lambda \n";
 return a < b;
 };

std::map<int, int, decltype(Lambda)> expt(Lambda);
expt[1] = 2;
expt[10] = 12;
auto search1 = expt.find(1);
auto search10 = expt.find(10);
if(search1 != expt.end()) {
    std::cout << "Found " << search1->first << " " << search1->second << '\n';
}
else {
    std::cout << "Not found\n";
}

Here is the output that I get:

Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Found 1 2

I am a bit confused about how find actually works in this case. Why do I get 7 calls of the lambda function even though I just have 2 keys in my map?

Author:Ashutosh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/44912675/understanding-stdmapfind
n. m. :

operator < cannot tell you that two things are equal in one go. You need to call both x < y and y < x in order to verify that x == y. So each time map actually finds a key, it compares the argument and the found key twice, once normally and once swapped around.\n\nThis accounts for double occurrence of lambda(1,1) and lambda(10,10). \n\nAs for lambda(10,1) and lambda(1,10) when inserting an element with the key of 10, this is needed because map may have to call comparison twice also when it fails to find a key (swap order of insertions to see that).",
2017-07-04T20:05:08
yy