现在的位置: 首页 > 综合 > 正文

使用静态“环形”数组建立一个队列

2013年10月11日 ⁄ 综合 ⁄ 共 1780字 ⁄ 字号 评论关闭


  1. /* 
  2.  *使用静态数组建立一个队列 
  3.  *我们采用把数组看成一个环形来循环利用数组, 
  4.  *使用m_size< QUEUE_CAPACITY+1来判断队列是否已满 
  5.  * 
  6.  *(对于模版类的定义,gcc4.4.5还不支持类的定义和实现的分离,要在 
  7.  *同一个文件中实现才能顺利编译,要注意怎样声明的operator <<( )的格式) 
  8.  * 
  9.  *queue(  ) 初始化一个队列 
  10.  *enqueue(  )  插入一个数据 
  11.  *dequeue(  ) 删除一个数据 
  12.  *display(  ) 显示一个队列的所有数据 
  13.  *opeartor <<(  ) 使用cout输出 
  14.  *empty(  ) 判断队列是否为空 
  15.  *front(  ) 获得队列的第一个值 
  16.  * 
  17.  *m_front 指向队列的首 
  18.  *m_back 指向队列的尾,下一个将要插入的地址 
  19.  *m_size 当前队列已有元素的数量 
  20.  */ 
  21. #ifndef ARRAY_QUEUE_H 
  22. #define ARRAY_QUEUE_H 
  23.  
  24. #include <iostream> 
  25. #include <cstdlib> 
  26. using std::ostream; 
  27. using std::cout; 
  28. using std::endl; 
  29.  
  30.  
  31. const int QUEUE_CAPACITY=128; 
  32.  //forward declare queue template 
  33. template<class T> class queue; 
  34.  
  35. //prototype for templatized operator<< 
  36. template<class T> 
  37. ostream& operator <<( ostream& out,const queue<T>& outqueue ); 
  38.  
  39. template<class T> 
  40. class queue 
  41. public
  42.     queue(  ); 
  43.      
  44.     bool empty( ) const
  45.     void enqueue( const T& value ); 
  46.     void dequeue(  ); 
  47.     void display(  ); 
  48.      
  49.     friend ostream& operator << <T>(ostream& out,const queue<T>& outqueue); 
  50.     T front(  ) const
  51.  
  52. private
  53.     int m_front; 
  54.     int m_back; 
  55.     int m_cursize; 
  56.      
  57.     T m_array[ QUEUE_CAPACITY ]; 
  58.      
  59.      
  60. }; 
  61.  
  62. template<class T> 
  63. ostream& operator <<(ostream& out,const queue<T>& outqueue) 
  64.     { 
  65.         int i=0; 
  66.         for( i=outqueue.m_front; i!=outqueue.m_back;i=(( i+1 )%QUEUE_CAPACITY )) 
  67.             out<<outqueue.m_array[ i ]<<" "
  68.         out<<'/n'
  69.         return out;    
  70.     } 
  71.  
  72. template<class T> 
  73. void queue<T>::display(  ) 
  74.     int i; 
  75.     for(i=m_front;i!=m_back;i=( i+1 )%QUEUE_CAPACITY) 
  76.         cout<<m_array[ i ]<<" "
  77.     cout<<endl; 
  78.  
  79.  
  80. template<class T> 
  81. queue<T>::queue(  ) 
  82.     { 
  83.         m_front=0; 
  84.         m_back=0; 
  85.         m_cursize=0; 
  86.     } 
  87.  
  88. template<class T> 
  89. bool queue<T>::empty(  ) const 
  90.     { 
  91.         return ( m_front==m_back ); 
【上篇】
【下篇】

抱歉!评论已关闭.