问题简述:如何重载运算符,使得排序和查找(find)的方式不同 。
具体来说: 一个结构体,node,它包含 x, y 两个元素,我按照先 x 后 y 的顺序重载比大小运算符。
bool operator < ( const node &tmp) const
{
if (x != tmp.x) return x < tmp.x;
return y < tmp.y;
}
但是我还想重载 s.find 时的运算符,即值比较 x 的值,忽略 y 的值。
bool operator == ( const node &tmp) const
{
return (x == tmp.x);
}
但是这样写貌似是不行的:
#include <cstdio>
#include <set>
using namespace std;
struct node
{
int x, y;
bool operator < ( const node &tmp) const
{
if (x != tmp.x) return x < tmp.x;
return y < tmp.y;
}
bool operator == ( const node &tmp) const
{
return (x == tmp.x);
}
void print()
{
printf("%d %d", x, y);
}
}a, b, c, d, e;
set <node> s;
int main()
{
a = (node){1, 2}; b = (node){1, 3}; c= (node){2, 3}, d = (node){3, 5};
s.insert(a); s.insert(b); s.insert(c); s.insert(d);
e = (node){1, 4};
if (s.find(e) != s.end()) printf("Yes\n");
else printf("No\n");
return 0;
}
结果输出的是 No,请问我应该怎么写。