【问题标题】:Overloading the == operator in custom implementation of a stack在堆栈的自定义实现中重载 == 运算符
【发布时间】:2015-07-19 14:29:41
【问题描述】:

我正在尝试实现一个始终返回 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 的最小元素(最小堆栈的顶部),如果它与主堆栈的顶部相同。

【问题讨论】:

  • 首先,关系运算符在两个操作数上都应该是const,而不仅仅是右手操作数。然后,你需要operator&lt; 来做你正在做的事情,而不是operator==。
  • @BenVoigt,所以你实际上是在建议我将其与那个进行比较。平等正是我想要超载的。
  • @Clockwork 我认为这个构造 node():T(NULL),next(NULL){} 是无效的不是吗?
  • @Clockwork 根据 C++ 标准“除非 mem-initializer-id 命名构造函数的类、构造函数类的非静态数据成员或该类的直接或虚拟基类,否则mem-initializer 格式不正确。”我认为您的意思是 data() 而不是 T( NULL )
  • @Clockwork 也许这个链接对你有用。 stackoverflow.com/questions/31409655/…

标签: c++ stack


【解决方案1】:

如果您已经拥有operator&lt;(任何类型的排序集合都需要它),那么有一个模式可以正确定义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;
}

【讨论】:

  • 我在这里有点困惑,不是在节点比较中同时比较数据和下一项的想法。通过取消引用,我们不仅仅是比较数据。
  • @Clockwork:这是operator== 的通常含义,它使用在operator&lt; 中检查的this 的任何成员。如果您对节点相等有其他含义,需要查看多个节点,我建议您给它一个更具描述性的名称,不要称它为operator==。如果您有两个项目 a 和 b 和 a&lt;b、b&lt;a、a==b 都是 false,标准库中的内容可能会中断。
猜你喜欢
  • 1970-01-01
  • 2016-04-14
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 2015-03-21
相关资源
最近更新 更多