• C++用数组实现的静态队列


    #ifndef _STATIC_QUEUE_H_
    #define _STATIC_QUEUE_H_
    
    // 静态queue模板,用数组实现的队列,在初始化的时候需要指定长度
    template<class T>
    class Static_Queue{
    public:
    	Static_Queue(unsigned int size);
    	virtual ~Static_Queue();
    	bool push(T t);
    	bool pop(T &t);
    	unsigned int GetElementCnt();
    	void dump();
    private:
    	unsigned int m_nSize;
    	T *m_arrT;
    	unsigned int m_nHead;
    	unsigned int m_nTail;
    	unsigned int m_nEmptyCnt;
    };
    
    template<class T>
    Static_Queue<T>::Static_Queue(unsigned int size)
    {
    	m_nSize = size;
    	m_arrT = new T[m_nSize];
    	memset(m_arrT,0,sizeof(T)*m_nSize);
    	m_nHead = 0;
    	m_nTail = 0;
    	m_nEmptyCnt = m_nSize;
    }
    
    template<class T>
    Static_Queue<T>::~Static_Queue()
    {
    	delete[] m_arrT;
    	m_arrT = NULL;
    }
    
    template<class T>
    bool Static_Queue<T>::push(T t)
    {
    	if( m_nEmptyCnt <= 0 )
    	{
    		return false;
    	}
    	m_arrT[m_nTail++] = t;
    	if(m_nTail >= m_nSize)
    	{
    		m_nTail = 0;
    	}
    	m_nEmptyCnt--;
    	return true;
    }
    
    template<class T>
    bool Static_Queue<T>::pop(T &t)
    {
    	if( m_nEmptyCnt >= m_nSize )
    	{
    		return false;
    	}
    	t = m_arrT[m_nHead++];
    	if( m_nHead >= m_nSize )
    	{
    		m_nHead = 0;
    	}
    	m_nEmptyCnt++;
    	return true;
    }
    
    template<class T>
    unsigned int Static_Queue<T>::GetElementCnt()
    {
    	return m_nSize - m_nEmptyCnt;
    }
    
    template<class T>
    void Static_Queue<T>::dump()
    {
    	cout<<"head= "<<m_nHead<<" "<<"tail= "<<m_nTail<<endl;
    	cout<<"[";
    	for(int i = 0;i < m_nSize;i++ )
    	{
    		cout<<m_arrT[i]<<" ";
    	}
    	cout<<"]"<<endl;
    }
    
    #endif
    

      测试代码:

    #include <iostream>
    #include "StaticQueue.h"
    using namespace std;
    
    int main()
    {
    	int i = 0;
    	int arr[] = {0,1,2,3,4,5,6,7,8,9};
    	Static_Queue<int> qu(8);
    	for(i = 0;i<10;i++)
    	{
    		if(qu.push(arr[i]) == false)
    		{
    			cout<<"push "<<arr[i]<<" fail"<<endl;
    		}
    	}
    	for(i  = 0;i < 5;i++)
    	{
    		int t = 0;
    		if(qu.pop(t) == true)
    		{
    			cout<<"pop "<<t<<endl;
    		}
    	}
    	for(i = 0;i<10;i++)
    	{
    		if(qu.push(arr[i]) == false)
    		{
    			cout<<"push "<<arr[i]<<" fail"<<endl;
    		}
    	}
    	for(i  = 0;i < 10;i++)
    	{
    		int t = 0;
    		if(qu.pop(t) == true)
    		{
    			cout<<"pop "<<t<<endl;
    		}
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    突然连不上VSS等服务器的原因之一
    “复制到剪贴板”的解决方案
    设置SQLServer2008开启远程连接(转)
    对List(IList)集合作求和,最大(小)值操作
    .net实现简单语音朗读(TTS)功能
    17点成就你的好代码
    2011年上半年五大臭名昭著的数据库泄密事件
    Spring Mobile 1.1.0.M2 发布
    Rainbows! 4.4.3 发布,修复 EventMachine 问题
    情绪不是反应,而是决定
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/4840794.html
Copyright © 2020-2023  润新知