I am making a Stack
which is based on linked-list
. Everything works fine except that I don't know how to implement a "range-based for loop" for this one.
I got the error: no match for ‘operator++’ (operand type is ‘Stack<int>::Node’)
.
What's wrong and how can I fix it?
Code (Foolish me overloads post ++
not prefix ++
, now all corrected.):
#include <iostream>
using namespace std;
template<typename T>
class Stack{
private:
class Node{
friend Stack;
public:
void operator++(){
this->next = this->next->next; //point to next Node
}
bool operator!=(const Node& rhs){
return !(*this == rhs);
}
T operator*(){
return this->next->elem; //return current Node elem
}
bool operator==(const Node& rhs){
return this->next == rhs.next;
}
private:
T elem;
Node* next;
};
Node* first;
int _size;
public:
Stack():_size(0){
first = nullptr;
}
void push(T item){
Node* n = new Node;
n->elem = item;
n->next = first;
first = n;
_size++;
}
T pop(){
T item = first->elem;
Node* old_first = first;
first = first->next;
delete old_first;
_size--;
return item;
}
int size(){
return _size;
}
bool empty(){
return _size == 0;
}
Node begin(){
Node n;
n.next = first;
return n;
}
Node end(){
Node m;
m.next = nullptr;
return m;
}
~Stack(){
Node* ele_to_delete;
while(first != nullptr){
ele_to_delete = first;
first = first->next;
delete ele_to_delete;
}
}
Stack(const Stack&) = delete;
Stack& operator=(const Stack&) = delete;
};
int main(){
Stack<int> ls;
ls.push(1);
ls.push(2);
ls.push(3);
for(auto s: ls){
cout << s << "|";
}
return 0;
}