- /*
- *使用静态数组建立一个队列
- *我们采用把数组看成一个环形来循环利用数组,
- *使用m_size< QUEUE_CAPACITY+1来判断队列是否已满
- *
- *(对于模版类的定义,gcc4.4.5还不支持类的定义和实现的分离,要在
- *同一个文件中实现才能顺利编译,要注意怎样声明的operator <<( )的格式)
- *
- *queue( ) 初始化一个队列
- *enqueue( ) 插入一个数据
- *dequeue( ) 删除一个数据
- *display( ) 显示一个队列的所有数据
- *opeartor <<( ) 使用cout输出
- *empty( ) 判断队列是否为空
- *front( ) 获得队列的第一个值
- *
- *m_front 指向队列的首
- *m_back 指向队列的尾,下一个将要插入的地址
- *m_size 当前队列已有元素的数量
- */
- #ifndef ARRAY_QUEUE_H
- #define ARRAY_QUEUE_H
- #include <iostream>
- #include <cstdlib>
- using std::ostream;
- using std::cout;
- using std::endl;
- const int QUEUE_CAPACITY=128;
- //forward declare queue template
- template<class T> class queue;
- //prototype for templatized operator<<
- template<class T>
- ostream& operator <<( ostream& out,const queue<T>& outqueue );
- template<class T>
- class queue
- {
- public:
- queue( );
- bool empty( ) const;
- void enqueue( const T& value );
- void dequeue( );
- void display( );
- friend ostream& operator << <T>(ostream& out,const queue<T>& outqueue);
- T front( ) const;
- private:
- int m_front;
- int m_back;
- int m_cursize;
- T m_array[ QUEUE_CAPACITY ];
- };
- template<class T>
- ostream& operator <<(ostream& out,const queue<T>& outqueue)
- {
- int i=0;
- for( i=outqueue.m_front; i!=outqueue.m_back;i=(( i+1 )%QUEUE_CAPACITY ))
- out<<outqueue.m_array[ i ]<<" ";
- out<<'/n';
- return out;
- }
- template<class T>
- void queue<T>::display( )
- {
- int i;
- for(i=m_front;i!=m_back;i=( i+1 )%QUEUE_CAPACITY)
- cout<<m_array[ i ]<<" ";
- cout<<endl;
- }
- template<class T>
- queue<T>::queue( )
- {
- m_front=0;
- m_back=0;
- m_cursize=0;
- }
- template<class T>
- bool queue<T>::empty( ) const
- {
- return ( m_front==m_back );
- }
- template<class T>
- void queue<T>::enqueue( const T& value )
- {
- int newBack=( m_back+1 )%QUEUE_CAPACITY;
- if( m_cursize < QUEUE_CAPACITY+1 )
- {
- //queue is not full
- m_array[m_back ]=value;
- m_back=newBack;
- ++m_cursize;
- }
- else
- {
- std::cerr<<"WARNING:Queue Is Full!!!/n";
- exit(-1);
- }
- }
- template<class T>
- void queue<T>::dequeue( )
- {
- if( !empty( ) )
- m_front=( m_front+1 )%QUEUE_CAPACITY;
- else
- std::cerr<<"Queue is empty,You can't remove a element!!!/n";
- }
- template<class T>
- T queue<T>::front( ) const
- {
- if( !empty( ) )
- return m_array[ m_front ];
- else
- {
- std::cerr<<"Queue is empty,nothing will be return./n";
- }
- }
- #endif
测试文件:
- #include "array_queue.h"
- #include <iostream>
- using std::cout;
- using std::endl;
- int main( )
- {
- queue<int> one;
- for( int i=1;i<21;++i )
- one.enqueue( i );
- cout<<endl;
- cout<<one;
- cout<<one.front( )<<"/n";
- one.dequeue( );
- one.dequeue( );
- cout<<one;
- return 0;
- }