以靜態方式實作堆疊
#include <iostream>
using namespace std;
template<typename T,int MAX_SIZE>
class SampleStack {
private:
T mem[MAX_SIZE];
int sp;
public:
SampleStack():sp(0) {}
inline const T pop() {
if(this->empty()) {
return T();
}
else {
return this->mem[--sp];
}
}
inline const bool push(const T &x) {
if(this->full()) {
return false;
}
else {
this->mem[sp++] = x;
return true;
}
}
inline const int size() {
return this->sp;
}
inline const bool full() {
return (this->sp >= MAX_SIZE);
}
inline const bool empty() {
return (this->sp == 0);
}
};
int main()
{
SampleStack<int, 3> t;
t.push(5);
t.push(3);
t.push(10);
cout << t.push(55) << endl;
cout << "Size: " << t.size()<<endl;
cout << "Pop 1: " << t.pop() << endl;
cout << "Pop 2: " << t.pop() << endl;
cout << "Pop 3: " << t.pop() << endl;
cout << "Pop 4: " << t.pop() << endl;
cout << "Size: " << t.size()<<endl;
return 0;
}