首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于栈:是重复输出还是异常原因

2012-07-30 
关于栈:是重复输出还是错误原因压入3个数进栈,使用5个弹出操作,可以“正常”运行,是重复输出还是错误输出[co

关于栈:是重复输出还是错误原因
压入3个数进栈,使用5个弹出操作,可以“正常”运行,是重复输出还是错误输出
[code=C/C++][/code]
#include<cstdlib>
#include<iostream>
using namespace std;

template<class T,int size = 100>//带有非类型参数的类模板,设置size的默认值为100
class Stack
{
  public:
  Stack():m_iCount(0) //Stack()是构造函数,m_iCount(0)初始化元素个数 
  { 
   
  }
  bool push(const T &e);//压入元素 
  bool pop(T &e); //弹出元素 
  int get_size() const //返回元素个数 
  {
  return m_iCount;
  }
  private:
  T m_iArray[size]; //栈中的元素用数组来存储 
  int m_iCount; //当前栈中元素的个数 
};


template<class T,int size>
bool Stack<T,size>::push(const T &e)
{
  if(m_iCount<size) //如果栈还没有满 
  {
  m_iArray[m_iCount++] = e; //加入元素到数组中 
  return true;
  }
  else
  {
  return false;
  }
}


template<class T,int size>
bool Stack<T, size>::pop(T &e)
{
  if(m_iCount >= 0) //如果栈中有元素 
  {
  e = m_iArray[--m_iCount]; //弹出元素 
  return true;
  }
  else
  {
  return false;
  }
}


int main(int argc,char *argv[])
{
  cout<<"---类模板实例化----"<<endl;
  Stack<int>iv; //用int型和默认的非类型参数值实例化类模板Stack
  iv.push(1); //依次压入3个整数 
  cout<<"压入1"<<endl;
  iv.push(2);
  cout<<"压入2"<<endl;
  iv.push(3);
  cout<<"压入3"<<endl;
  cout<<"元素个数: "<<iv.get_size()<<endl<<endl;
   
  cout<<"弹出元素: " ;
  int e = 0;  
  iv.pop( e ); //弹出元素 
  cout<<e<<endl;
  cout<<"弹出元素: " ;
  iv.pop( e ); //弹出元素 
  cout<<e<<endl;
  cout<<"弹出元素: " ;
  iv.pop( e ); //弹出元素 
  cout<<e<<endl;
  cout<<"弹出元素: " ;
  iv.pop( e ); //弹出元素 
  cout<<e<<endl;
  cout<<"弹出元素: " ;
  iv.pop( e ); //弹出元素 
  cout<<e<<endl;
  cout<<"元素个数: "<<iv.get_size()<<endl;
   
  system("PAUSE");
  return EXIT_SUCCESS;

 

[解决办法]
3个数进栈,使用5个弹出操作???怎么弹出5个的???

热点排行