Reputation: 1833
I have understood that we have to write the operator overloading function for < operator when we have using the key as struct since the map uses the strict week ordering it has to compare before inserting in to map.
Hope my understanding is correct by reading from here.
consider the following snippet
struct Node
{
int a;
};
// This is not called
bool operator< (const Node &p_node1,const Node &p_node2)
{
printf("\nCALLED OPERATOR OVERLOADING");
return true;
}
int main()
{
using namespace std;
map<Node,int> my_map;
Node n1;
n1.a=55;
my_map[n1]=2; // operator overloading should be called
return 0;
}
And the issue is operator overloading function not called?
EDIT:
From the answer below, After adding the one more pair to container operator overloading is called. But why it is called three times specifically, what is compared here?
Upvotes: 2
Views: 222
Reputation: 3387
Have atleast 2 elements in map for comparison operator to be called.
Node n1;
n1.a=55;
my_map[n1]=2; // operator overloading should be called
Node n2;
n2.a=55;
my_map[n2]=3;
See below modified example code.
Upvotes: 0
Reputation: 70931
You are inserting the only element in an empty map and so the comparison operator is never called. Try having more than one element in my_map
.
Upvotes: 2
Reputation: 1638
When the map is empty, the comparator does not need to be invoked because there is nothing to compare against to.
Upvotes: 6