[英]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.