gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:09:50 24 4
gpt4 key购买 nike

我正在尝试实现一个始终返回最小元素的自定义堆栈。因此,我有效地维护了两个堆栈。我已经在我的自定义堆栈中实现了 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;
}

关于c++ - 在堆栈的自定义实现中重载 == 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com