#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template<class T,int ssize = 100>
class Stack
{
private:
T stack[ssize];
int top;
public:
Stack() : top(0){}
void push(const T& i)
{
if (top <ssize)// 這個是判斷條件,
stack[top++] = i;
}
T pop() // 每pop一次堆棧裏邊就少一個數據,
{
if (top > 0) // 這個是判斷條件,
return stack[--top];
}
class iterator;
friend class iterator;
class iterator // 這個是做堆棧的迭代器,迭代器不會改變堆棧裏邊的數據,只能講數據讀取出來看,
{
private:
Stack& s;
int index; // 索引,
public:
iterator(Stack& is) : s(is), index(0) {}
iterator(Stack& is, bool) :s(is), index(s.top){}
T operator*() const { return s.stack[index]; }
T operator++() // 操作符重載前加加,
{
if (index < s.top)
return s.stack[++index];
}
T 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()
{
Stack<int> a;
a.push(8);
a.push(9);
a.push(10);
a.push(11);
//IntStack::iterator it(a);
Stack<int>::iterator it(a.begin());
while (it != a.end())
{
cout << it++ << endl;
}
cout << endl;
Stack<int>::iterator start = a.begin();
start += 2;
cout << *start<< endl;
Stack<string> strings;
ifstream in("naintest.cpp"); // 這個在函數頭 #include <fstream> 裏邊,
string line;
while (getline(in, line))
strings.push(line);
Stack<string>::iterator rb = strings.begin(), rs = strings.end();
while (rb != rs)
cout << rb++ << endl;
/*for (int i = 0; i < 4; i++)
cout << it++ << endl; */ // 前加加輸出9 10 11 還有一個隨機數,後加加輸出8 9 10 11
return 0;
}
模板迭代器
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.