• 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;
    }
    

      

  • 相关阅读:
    vue导航守卫和axios拦截器的区别
    js中的深拷贝与浅拷贝
    Storyboard中拖拽控件不能运行的问题(在运行的时候,相应的控件代码没有被执行)
    关于stringWithFormat:
    两层嵌套的JSON包的解法
    button的action属性如果有参数,必须加“:”
    iOS 协同开发出fatal error: file 'XX-Prefix.pch' has been modified since the precompiled header was built
    [转] Objective-C语法快速参考
    iOS应用程序内存查看工具
    XCode快捷键大全
  • 原文地址:https://www.cnblogs.com/tangxin-blog/p/4840794.html
Copyright © 2020-2023  润新知