<在map中使用struct作为键时未调用操作符

overloading of < operator not called when using struct as key in map?

本文关键字:调用操作符 struct map      更新时间:2023-10-16

我明白了,我们必须为<操作符>

希望我的理解是正确的。

考虑下面的代码片段

  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;
    }

问题是操作符重载函数没有调用?

编辑:

从下面的答案中,在向容器中再添加一对操作符后,调用重载操作符。但是为什么它被称为三次,这里比较了什么?

当映射为空时,不需要调用比较器,因为没有东西可以比较。

在空映射中插入唯一的元素,因此永远不会调用比较操作符。尝试在my_map中拥有多个元素。

map中至少有2个元素用于调用比较操作符

       Node n1;
       n1.a=55;
       my_map[n1]=2; // operator overloading should be called
       Node n2;
       n2.a=55;
       my_map[n2]=3;

见下面修改后的示例代码。

http://ideone.com/iGY9Xa