標準輸出如下
Now, intStack is full.
9 9 9 9 9 9 9 9 9 9
9 8 7 6 5 4 3 2 1 0
Now, intStack is empty.
There are 5 elements in stringStack.
Now, there are no elements in stringStack
我的問題代碼如下
#include<iostream>
using namespace std;
template<class T, int SIZE = 20>
class Stack{
private:
T array[SIZE]; //陣列,用于存放堆疊的元素
int top; //堆疊頂位置(陣列下標)
public:
Stack(); //建構式,初始化堆疊
void push(const T & ); //元素入堆疊
T pop(); //堆疊頂元素出堆疊
void clear(); //將堆疊清空
const T & Top() const; //訪問堆疊頂元素
bool empty() const; //測驗堆疊是否為空
bool full() const; //測驗是否堆疊滿
int size(); //回傳當前堆疊中元素個數
};
template<class T, int SIZE>
Stack<T,SIZE>::Stack(){
top=0;
}
template<class T, int SIZE>
void Stack<T,SIZE>::push(const T &a )
{
top=top+1;
array[top]=a;
}
template<class T, int SIZE>
T Stack<T,SIZE>::pop()
{
T t=array[top];
top=top-1;
cout<<t<<endl;
return t;
}
template<class T, int SIZE>
void Stack<T,SIZE>::clear()
{
delete[]array;
}
template<class T, int SIZE>
const T &Stack<T,SIZE>::Top() const
{
T t=array[top];
return t;
}
template<class T, int SIZE>
bool Stack<T,SIZE>::empty() const
{
if(top==0)return true;
else return false;
}
template<class T, int SIZE>
bool Stack<T,SIZE>::full() const
{
if(top==SIZE)return true;
else return false;
}
template<class T, int SIZE>
int Stack<T,SIZE>::size()
{
return top;
}
int main()
{
Stack<int,10> intStack;
for(int i=0;i<10;i++)
intStack.push(i);
if(intStack.full()) cout<<"Now, intStack is full."<<endl;
for(int i=0;i<10;i++)
cout<<intStack.Top()<<" ";
cout<<endl;
for(int i=0;i<10;i++)
cout<<intStack.pop()<<" ";
cout<<endl;
if(intStack.empty())
cout<<"Now, intStack is empty."<<endl;
Stack<string,5> stringStack;
stringStack.push("One");
stringStack.push("Two");
stringStack.push("Three");
stringStack.push("Four");
stringStack.push("Five");
cout<<"There are "<<stringStack.size()<<" elements in stringStack."<<endl;
stringStack.clear();
if(stringStack.empty())
cout<<"Now, there are no elements in stringStack"<<endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/61493.html
標籤:基礎類
上一篇:opengl
