Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding std::map::find

Tags:

c++

c++11

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?

like image 586
Ashutosh Avatar asked Jul 04 '17 19:07

Ashutosh


1 Answers

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.

This accounts for double occurrence of lambda(1,1) and lambda(10,10).

As 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).

like image 184
n. 1.8e9-where's-my-share m. Avatar answered Oct 28 '22 16:10

n. 1.8e9-where's-my-share m.