繁体   English   中英

在堆栈的自定义实现中重载==运算符

[英]Overloading the == operator in custom implementation of a stack

我正在尝试实现一个始终返回min元素的自定义堆栈。 因此,有效地我保持了两个堆栈。 我已经在自定义堆栈中实现了push方法,但是在实现pop时会感到有些茫然。 理想情况下,我尝试为==运算符编写两个两个比较两个节点的自定义重载。 这是我的节点实现。

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;

};

这是我的堆栈推送和弹出

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;

    }

这是我为相等重载定义的方法签名。

bool operator==(const node<T>& other){

    }

这个想法是弹出min_stack的最小元素(最小堆栈的顶部),如果它与主堆栈的顶部相同。

如果您已经有了operator< (需要任何类型的排序集合),那么就有一种模式可以正确定义operator==

bool operator==(const node<T>& other) const
{
    if (*this < other) return false;
    if (other < *this) return false;
    return true;
}

或者,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM