循环队列(RingBuff)C++实现

RingBuff.h实现:

#include 

using namespace std;

template <class T>
class RingBuff
{
private:
    unsigned int m_size;
    int m_in;
    int m_out;
    T* m_data;

public:
    RingBuff (unsigned int size)
            : m_size(size)
            , m_in(0)
            , m_out(0)
    {
        m_data = new T[m_size];
    }

    ~RingBuff() {
        delete[] m_data;
    }

    bool isEmpty() {
        return m_in == m_out;
    }

    bool isFull() {
        return m_out == (m_in + 1) % m_size;
    }

    void push(T ele) {
        if (isFull()) {
            return;
        }

        m_data[m_in] = ele;
        m_in = (m_in + 1) % m_size;
    }

    T pop() {
        if (isEmpty()) {
            return NULL;
        }

        T tmp = m_data[m_out];
        m_out = (m_out + 1) % m_size;
        return tmp;
    }
};

main函数实现:

#include "RingBuff.h"

using namespace std;

int main()
{
    cout << "Hello CMake。" << endl;

    RingBuff<char> ringBuff(11);
    char a = '0';
    for (int i = 0; i < 1024; i++) {
        //arr[i] = a++;
        ringBuff.push(a++);
    }

    while (!ringBuff.isEmpty()) {
        printf("%c ", ringBuff.pop());
    }

    RingBuff<int> ringBuffInt(1024);
    for (int i = 0; i < 1024; i++) {
        //arr[i] = a++;
        ringBuffInt.push(i);
    }

    while (!ringBuffInt.isEmpty()) {
        printf("%d ", ringBuffInt.pop());
    }
    int b = ringBuffInt.pop();
    printf("%d\n", b);

    getchar();
    return 0;
}

你可能感兴趣的:(C++)