gpt4 book ai didi

c++ - 运算符 > 重载不起作用

转载 作者:行者123 更新时间:2023-11-27 22:51:20 25 4
gpt4 key购买 nike

之前我已经重载了operator <我已经对结构进行了排序。

现在我正在尝试重载 operator >但它不起作用(实际上甚至无法编译)。我需要一些帮助来找出查询。

#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
struct a
{
int num1;
int num2;
bool operator > (const a& rhs) const
{
return num1>rhs.num1;
}
};

int main()
{
a array[1000];
for(int i=0; i<2; i++)
{
cin>>array[i].num1>>array[i].num2;
}
sort(array, array+2);
for(int i=0; i<2; i++)
{
cout<<array[i].num1<<" "<<array[i].num2<<endl;
}
}

最佳答案

当查看 std::sort 时我们可以看到使用带有 2 个参数的重载时:

1) Elements are compared using operator<

这意味着如果您的自定义类型没有定义 operator<你会得到一个编译器错误。如果您不想重载此运算符,则可以使用自定义比较器作为第三个参数。或者,您可以反转 operator> 的结果:

bool operator < (const a& rhs) const
{
return !(num1>rhs.num1);
}

关于c++ - 运算符 > 重载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com