【发布时间】:2021-07-03 15:27:30
【问题描述】:
当我运行以下代码(注释掉一行)时,我没有得到任何输出(没有进行比较)。 但是在我取消注释最后一行的那一刻,我得到了三行输出(进行了三个比较)。添加第二项时,1-2 比较是可以理解的,但为什么要添加第三项呢?
#include <map>
#include <iostream>
using namespace std;
class MyType
{
public :
int a;
MyType():a(0){}
};
bool operator<(const MyType &lhs, const MyType &rhs)
{
cout<<"operator < is called\n";
return lhs.a < rhs.a;
}
int main()
{
MyType T1,T2;
T1.a = 100;
T2.a = 33;
map<MyType,int> Test;
Test[T1] = 10;
//Test[T2] = 20; --> #Uncomment this line for getting 3 lines of "operator < is called"
}
未注释行的输出:
operator < is called
operator < is called
operator < is called
它是如何在只添加一个额外键的情况下从零开始打印三个字符串的?
这里是lhs和rhs的地址:
0x56365ea45e90
0x7ffe3c4cd47c
operator < is called
0x7ffe3c4cd47c
0x56365ea45e90
operator < is called
0x56365ea462d0
0x56365ea45e90
operator < is called
【问题讨论】:
-
就像插入 USB 设备一样。尝试第一种方法失败,尝试第二种方法失败,再次尝试第一种方法并插入。
-
当您将第一个项目添加到地图时,它是空的,没有什么可比较的。
-
在我的系统 (clang-cl) 上,
<运算符被调用了两次。我想这是实现定义的如何实现std::map容器及其操作符。 -
@MarkRansom:是的,但是当添加第二项时,1-2 比较是可以的,但为什么第三项?
-
在我看来,这与地图有关,而不是运算符重载。如果没有重载,将会有 3 次比较——您只是无法计算比较。