#include <iostream>
using namespace std;
class IntStack
{
private:
enum {ssize = 100};
int stack[ssize];
int top;
public:
IntStack() : top(0){}
//~IntStack(){}
void push(int i)
{
if (top <ssize)// 這個是判斷條件,
stack[top++] = i;
}
int pop() // 每pop一次堆棧裏邊就少一個數據,
{
if (top > 0) // 這個是判斷條件,
return stack[--top];
}
class iterator;
friend class iterator;
class iterator // 這個是做堆棧的迭代器,迭代器不會改變堆棧裏邊的數據,只能講數據讀取出來看,
{
private:
IntStack& s;
int index; // 索引,
public:
iterator(IntStack& is) : s(is), index(0) {}
iterator(IntStack& is, bool) :s(is), index(s.top){}
int current() const { return s.stack[index]; }
int operator++() // 操作符重載前加加,
{
if (index < s.top)
return s.stack[++index];
}
int operator++(int)
{
if (index < s.top)
return s.stack[index++];
}
iterator& operator+=(int amount)
{
index += amount;
return *this;
}
bool operator==(const iterator& rv) const
{
return index == rv.index;
}
bool operator!=(const iterator& rc) const
{
return index != rc.index;
}
friend ostream& operator<<(ostream& os, const iterator& it) // 輸出流操作符重載,
{
return os << it.current();
}
};
iterator begin() // begin 指向堆棧的第一個數據,
{
return iterator(*this);
}
iterator end() // end指向堆棧的最後一個數據的下一個,
{
return iterator(*this, true);
}
};
int main()
{
IntStack a;
a.push(8);
a.push(9);
a.push(10);
a.push(11);
//IntStack::iterator it(a);
IntStack::iterator it(a.begin());
while (it != a.end())
{
cout << it++ << endl;
}
cout << endl;
IntStack::iterator start = a.begin();
start += 2;
cout << start.current() << endl;
/*for (int i = 0; i < 4; i++)
cout << it++ << endl; */ // 前加加輸出9 10 11 還有一個隨機數,後加加輸出8 9 10 11
return 0;
}
堆棧裏的迭代器
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.