![](https://iknow-base.cdn.bcebos.com/lxb/notice.png)
一道C++题目,栈的数据成员是5个整型的数组该怎么做啊?求解,最好能给段代码,用C或C++,先谢过了
using namespace std;
class Stack
{
public:
Stack(size_t uCapacity):m_pArray(new void*[uCapacity]),m_uCapacity(uCapacity),m_uTop(0){}
~Stack(void)
{
if(m_pArray)
{
delete[]m_pArray;
m_pArray=NULL;
}
m_uCapacity=0;
m_uTop=0;
}
void Push(void* pData)//实现压入
{
if(m_uTop>=m_uCapacity)
throw OverFlow();
m_pArray[m_uTop++]=pData;
}
void* Pop(void)//实现弹出
{
if(!m_uTop)
throw UnderFlow();
return m_pArray[--m_uTop];
}
private:
//上溢异常
class OverFlow:public exception
{
public:
const char*what(void)const throw()
{
return"stack::over_flow";
}
};
//下溢异常
class UnderFlow:public exception
{
public:
const char*what(void)const throw()
{
return"stack::under_flow";
}
};
void** m_pArray;//数组
size_t m_uCapacity;//容量
size_t m_uTop;//栈顶
};
class User
{
public:
User(const char*pszName,int nAge):m_strName(pszName),m_nAge(nAge){}
friend ostream&operator<<(ostream&os,const User&user)
{
return os<<user.m_strName<<" "<<user.m_nAge;
}
private:
string m_strName;
int m_nAge;
};
int main()
{
try
{
Stack stack(5);
stack.Push(new User("USER_1",10));
stack.Push(new User("USER_2",20));
stack.Push(new User("USER_3",30));
stack.Push(new User("USER_4",40));
stack.Push(new User("USER_5",50));
//stack.Push(new User("USER_6",60));
cout<<*static_cast<User*>(stack.Pop())<<endl;
cout<<*static_cast<User*>(stack.Pop())<<endl;
cout<<*static_cast<User*>(stack.Pop())<<endl;
cout<<*static_cast<User*>(stack.Pop())<<endl;
cout<<*static_cast<User*>(stack.Pop())<<endl;
//cout<<*static_cast<User*>(stack.Pop())<<endl;
}
catch(exception& ex)
{
cout<<ex.what()<<endl;
return -1;
}
return 0;
}
#include <iostream>
#include <memory.h>
using namespace std;
class Stack
{
private:
int a[5];
int tail;
int n;
public:
Stack()
{
memset(a, 0, 5);
tail = 0;
n = 0;
}
void Push(int x)
{
if(n == 5)
{
cout<<"Stack overflow"<<endl;
return;
}
a[tail ++] = x;
n ++;
}
int Gettop()
{
return a[tail];
}
void Pop()
{
tail --;
n --;
}
bool Isempty()
{
if(n == 0)
return 1;
else return 0;
}
int getl()
{
return n;
}
};
int main()
{
Stack s;
int a[6] = {1,5,9,2,4,10};
for(int i = 0; i < 6; i ++)
s.Push(a[i]);
int top = s.Gettop();
cout<<top<<endl;
s.Pop();
if(s.Isempty())
cout<<"Empty"<<endl;
else
cout<<s.getl()<<endl;
return 0;
}
#include <stack>
template < typename T, typename Container = deque<T> >
class mystack : public std::stack<T, Container>
{
mystack(void) {}
~mystack(void) {}
};
mystack<int> s; //创建栈
s.push(n); //将自定义元素依次入栈
s.top(); // 读取并输出栈顶元素
s.pop(); // 退栈
s.size(); // 取长度
s.empty();//是否为空
这样就全有了, 最懒的办法
可不可以不用STL啊?题目要求自己编写而不是使用现成的模板=。=#
那就去用楼上的