c++中用类模板来定义顺序栈类
答案:1 悬赏:60 手机版
解决时间 2021-05-11 01:04
- 提问者网友:浩歌待明月
- 2021-05-10 18:41
c++中用类模板来定义顺序栈类
最佳答案
- 五星知识达人网友:想偏头吻你
- 2021-05-10 18:52
#include <iostream>
using namespace std;
template <class T>
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<int> a(10);
stack<char> b(10);
stack<double> 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;
}
附图:
using namespace std;
template <class T>
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<int> a(10);
stack<char> b(10);
stack<double> 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;
}
附图:
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯