[英]Overloading the == operator in custom implementation of a stack
I'm trying to implement a custom stack that always returns the min element. 我正在尝试实现一个始终返回min元素的自定义堆栈。 Effectively thus I'm maintaining two stacks.
因此,有效地我保持了两个堆栈。 I've implemented the push method in my custom stack but feel at a bit of a loss implementing the pop.
我已经在自定义堆栈中实现了push方法,但是在实现pop时会感到有些茫然。 Ideally I'm trying to write a custom overload of for the == operator two compare two nodes.
理想情况下,我尝试为==运算符编写两个两个比较两个节点的自定义重载。 This is my node implementation.
这是我的节点实现。
template<typename T> class stack;
template<typename T> class node{
friend class stack<T>;
public:
node():T(NULL),next(NULL){}
node(T data):data(data), next(NULL){}
private:
T data;
node<T>* next;
};
And here's my stack push and pop 这是我的堆栈推送和弹出
void push(T item){
node<T>* N = new node<T>(item);
if(top == nullptr){
top = N;
min_top = N;
++elements;
return;
}
if(item < min_top->data) N->next = min_top;
min_top = N;
N->next = top;
top = N;
++elements;
}
........... ........... ........... ...........
T pop(){
if(top == nullptr)throw std::runtime_error("stack empty");
T item = top->data;
node<T>* P = top;
top = P->next;
delete P;
--elements;
return item;
}
This is the method signature I've defined for the equality overload. 这是我为相等重载定义的方法签名。
bool operator==(const node<T>& other){
}
The idea is to pop the minimum element(top of the min stack) of the min_stack if it's the same as the top of the main stack. 这个想法是弹出min_stack的最小元素(最小堆栈的顶部),如果它与主堆栈的顶部相同。
If you already have operator<
(which you need for a sorted collection of any type), then there's a pattern for correctly defining operator==
: 如果您已经有了
operator<
(需要任何类型的排序集合),那么就有一种模式可以正确定义operator==
:
bool operator==(const node<T>& other) const
{
if (*this < other) return false;
if (other < *this) return false;
return true;
}
Or you can make it even more general using std::less
: 或者,您可以使用
std::less
使它更加通用:
bool operator==(const node<T>& other) const
{
using std::less;
if (less(*this, other)) return false;
if (less(other, *this)) return false;
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.