[英]C++ user-defined operator< not working properly
I have a struct Node and I want to define operator< for it in order to use the Node in my Fibonacci Heap. 我有一个struct Node,我想为它定义operator <,以便在我的Fibonacci Heap中使用Node。
This is my simple Node: 这是我的简单节点:
struct Node {
int key, data;
Node* parent;
Node(int aKey, int aData):key(aKey),data(aData),parent(nullptr) {}
bool operator<(const Node* n) const {
return n->key > key;
}
}
To make sure operator< was working, I tested it out: 为了确保operator <正在运行,我测试了它:
Node* n = new Node(100, 0);
Node* m = new Node(1, 1);
cout << (n < m) << endl;
cout << (n > m) << endl;
The answer I got was: 我得到的答案是:
1
0
However, I suspected this was wrong so I modified my Node a bit: 但是,我怀疑这是错误的所以我修改了我的节点:
struct Node {
int key, data;
Node* parent;
Node(int aKey, int aData):key(aKey),data(aData),parent(nullptr) {}
bool operator<(const Node* n) const {
cout << "comparing.... " << endl;
return n->key > key;
}
}
Then I did the same test again, and "comparing.... " never printed out. 然后我又做了同样的测试,“比较....”从未打印出来。 So for some reason, when I try to compare Nodes, it doesn't use the comparator operator that I have defined.
因此,出于某种原因,当我尝试比较节点时,它不使用我定义的比较器运算符。 Instead, it appears to me comparing the pointers.
相反,在我看来比较指针。 How do I fix this?
我该如何解决? I know that the "alternative" would be to create something like:
我知道“替代”将是创建类似的东西:
struct NodeComp(Node* a, Node* b) {
....
}
However, that won't work for my implementation of the Fibonacci Heap, and ultimately I want to insert the Nodes into the Fibonacci Heap. 但是,这对我实现Fibonacci Heap不起作用,最终我想将节点插入Fibonacci Heap。
Thanks. 谢谢。
Normal use of operator<
involves passing a const reference parameter, not a pointer: 正常使用
operator<
涉及传递const引用参数,而不是指针:
bool operator<(const Node& n) const { // Note the & instead of the *
return n.key > key;
}
You can then compare Node
pointers by first dereferencing them: 然后,您可以通过首先取消引用它们来比较
Node
指针:
cout << (*n < *m) << endl;
Regardless , you're not going to get >
to work if you've only defined <
-- you'll need to also overload operator>
if you want to be able to compile expressions like (*n > *m)
. 无论如何 ,你不会得到
>
如果你只定义工作<
-你还需要重载operator>
如果您希望能够编译般的表情(*n > *m)
If you want to overload operator<()
it needs to be made either a member of the class: 如果要重载
operator<()
则需要将其作为类的成员:
bool operator<(Node &n);
It can also be a stand-alone function: 它也可以是一个独立的功能:
// this function should be made a friend of you class if you need to
// access private class members
bool operator<(Node &left, Node &right);
Note that a reference to the object is passed to your function, not a pointer. 请注意,对象的引用将传递给您的函数,而不是指针。
You will need to rewrite your code to: 您需要将代码重写为:
cout << (*n < *m) << endl;
cout << (*n > *m) << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.