c++中用类模板来定义顺序栈类

2024-11-22 18:02:04
推荐回答(1个)
回答(1):

#include
using namespace std;

template
class stack {
public:
stack(T n)
: base(new T[n]), sp(base), size(0), capacity(n)
{ }

T push(T n) {
*sp++ = n;
++size;
return n;
}
T pop() {
return *--sp;
}

void dump() const {
for(T* p = base; p != sp; ++p)
cout << *p << ' ';
cout.put('\n');
}

bool empty() const {
return sp == base;
}

~stack() {
if(capacity != 0)
delete [] base;
}
private:
T* base;
T* sp;
int size;
const int capacity;
};

#define PUSH( s, a, b ) for( i = 0; i < b; ++i ) s.push( a+i );
#define POP( a ) while( !a.empty() ) cout << a.pop() << ' '; cout.put( '\n' );
int main()
{
stack a(10);
stack b(10);
stack c(10);
int i;
PUSH( a, 1, 3 );
PUSH( b, 'a', 5 );
PUSH( c, 1.1, 8 );
a.dump(); b.dump(); c.dump();
POP( a ); POP( b ); POP( c );
return 0;
}

附图: