STL 循环队列编写

在c++linux系统编程模块,循环队列是很重要的一部分(示意图如下),但是c++ stl库却没有给出一个容器去存储,既然没有轮子,就由我们自己造轮子

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

template
class squeue
{
private:
    bool m_inited;
    TT m_data[MaxLength];
    int m_head;
    int m_tail;
    int m_length;

    // 禁止拷贝构造和赋值操作
    squeue(const squeue&) = delete;
    squeue& operator=(const squeue&) = delete;

public:
    squeue() {
        init();
    }

    void init() {
        if (!m_inited) {
            m_head = 0;
            m_tail = MaxLength - 1;
            m_length = 0;
            memset(m_data, 0, sizeof(m_data)); // 修正拼写错误:meset -> memset
            m_inited = true;
        }
    }

    bool push(const TT& ee) {
        if (full()) {
            cout << "add fail" << endl;
            return false;
        } else {
            m_tail = (m_tail + 1) % MaxLength;
            m_data[m_tail] = ee;
            m_length++;
        }
        return true;
    }

    int size() {
        return m_length;
    }

    bool empty() {
        if (m_length == 0) return true; // 修正拼写错误:m_lenth -> m_length
        return false;
    }

    bool full() {
        if (m_length == MaxLength) return true; // 修正拼写错误:MaxLenth -> MaxLength
        return false;
    }

    TT& front() {
        return m_data[m_head];
    }

    bool pop() {
        if (empty()) { // 修正:直接调用empty()函数
            return false;
        } else {
            m_head = (m_head + 1) % MaxLength;
            m_length--;
        }
        return true;
    }

    bool printsqueue() const { // 添加const修饰符
        for (int ii = 0; ii < m_length; ii++) {
            cout << m_data[(m_head + ii) % MaxLength] << endl;
        }
        return true; // 添加返回值
    }

    TT& back() {
        return m_data[m_tail];
    }
};
在linux和windows下面结果一样,有些头文件是博主为了方便后续代码写的,大家可以忽略。