发展循环数组C ++

时间:2017-10-06 00:10:17

标签: c++ arrays queue

我正在尝试以数组的形式编写一个通用队列。如果我将arraySize设置为特定值,但是如果我每次尝试填充数组时它都会被覆盖,那么一切似乎都有效。我很欣赏有关我做错的任何建议。感谢

HEADER:

#ifndef QUEUE_ARRAY
#define QUEUE_ARRAY

template <typename E>
class Queue {
public:
    Queue();            //constructor
    //Queue(const Queue &obj);  //copy constructor note:the copy constructor is optional
    ~Queue();           //destructor
    void enqueue(const E& e);
    const E& dequeue(); //throw(QueueEmpty);  //note that the use of exceptions is optional
    const E& front() const; //throw(QueueEmpty); //note that the use of exceptions is optional
    int size() const;
    bool empty() const;

private:
    int frontElem, rear, numEntries, arraySize;
    E* queueArray;
};
#endif // 

QA CPP:

#include "QueueArray.h"
#include <iostream>

template<typename E>
Queue<E>::Queue() {
    numEntries = 0;
    arraySize = 1;
    frontElem = 0;
    rear = 0;
    queueArray = new E[arraySize];
}

template<typename E>
Queue<E>::~Queue() {
    delete[] queueArray;
}

template<typename E>
void Queue<E>::enqueue(const E & e) {

    if (numEntries == arraySize) {
        arraySize = arraySize * 2;
        E* temp = new E[arraySize];
        for (int i = 0; i < numEntries; i++) {
            temp[i] = queueArray[(frontElem + i) % arraySize];
        }
        delete queueArray;
        queueArray = temp;
    }
    queueArray[rear] = e;
    rear = (rear + 1) % arraySize;
    numEntries++;
}

template<typename E>
const E& Queue<E>::dequeue() {

    E &temp = queueArray[frontElem];
    frontElem = ((frontElem + 1) % arraySize);
    numEntries--;

    return temp;
}

template<typename E>
const E& Queue<E>::front() const {
    return queueArray[frontElem];
}

template<typename E>
int Queue<E>::size() const {

    return numEntries;
}

template<typename E>
bool Queue<E>::empty() const {

    return (numEntries == 0);
}

QA EXPAND:

#include "QueueArray.cpp"

using namespace std;

template class Queue<int>;

QA TEST:

#include "QueueArray.h"
#include <iostream>

using namespace std;

int main() {

    Queue<int> *s;
    s = new Queue<int>();

    for (int i = 1; i <= 25; i++){
        s->enqueue(i);
    }

    while (!s->empty()) {
        cout << "Dequeue: " << s->dequeue() << endl;
    }

    system("PAUSE");

    delete s;
}

1 个答案:

答案 0 :(得分:0)

将现有队列数据复制到enqueue中新分配的缓冲区时,将元素frontElem处的元素复制到元素0.您没有,需要的是{{ 1}}复制数据后。 frontElem = 0;也需要更新。

rear应为delete queueArray。由于您正在分配数组,因此需要删除数组。