I am trying to understand the behavior of this following piece of code.
#include <iostream>
#include <string>
#include <set>
using namespace std;
struct cmp {
bool operator() (int a, int b) const {
cout<<"This is a-->"<<a<<" "<<endl;
cout<<"This is b-->"<<b<<" "<<endl;
return a < b;
}
};
int main() {
set<int, cmp> s;
s.insert(1);
s.insert(10);
//s.insert(11);
//s.insert(100);
for (int x : s)
cout << x << ' ';
return 0;
}
The output that I am getting for this is
This is a-->10
This is b-->1
This is a-->1
This is b-->10
This is a-->10
This is b-->1
1 10
I understand what this code does is that it sorts the elements of the set in ascending order but why is the comparator is being called 3 times? And why in the first case a is 10 but in the second case a is 1 and again in the third case it is 10?
And when I modify the code slightly to store the elements in the decreasing order, like below
#include <iostream>
#include <string>
#include <set>
using namespace std;
struct cmp {
bool operator() (int a, int b) const {
cout<<"This is a-->"<<a<<" "<<endl;
cout<<"This is b-->"<<b<<" "<<endl;
return a > b;
}
};
int main() {
set<int, cmp> s;
s.insert(1);
s.insert(10);
//s.insert(11);
//s.insert(100);
for (int x : s)
cout << x << ' ';
return 0;
}
Then why is the comparator function is being called only twice as seen in the output?
This is a-->10
This is b-->1
This is a-->10
This is b-->1
10 1
It will be of great help if anyone can shed some light on this.