C++ 固定長度的隊列


 

因為有需求,需要程序在內存大小保存不變來保存數據,但是數據的取用又是按隊列的來操作,節約時間節約內存,但是c++基礎又不太好.

#include <iostream>
#include <string>

using namespace std;


typedef struct NN {
    string data;
} Node;

class FixedQueue {
    public:
        int length;
        FixedQueue(int size) {
            this->size = size; // 容器的大小 
            this->init();
            // 分配內存 
            this->data = new Node[size];
        }
        void init() {
            this->length = this->startp = 0;
            this->endp = -1;
        }
     // 出隊 Node
* pop() { if (!empty()) { int geti = this->startp; this->startp++; if (this->startp < 0) { this->startp = this->size; } this->length--; return &(this->data[geti]); } //cout << "隊列為空!" << endl; return NULL; } // 相當於入隊 Node * getNode() { if (!full()) { this->endp = (this->endp+1)%(this->size); //cout << "正在獲取一個節點: " << this->data[i].data << endl; this->length++; //cout << "分配一個節點" << endl; return &this->data[this->endp]; } cout << "隊列已滿" << endl; return NULL; } bool empty() { if (this->length == 0) { this->init(); return true; } return false; } bool full() { return this->size == this->length; } void print() { cout << this->startp << ":" << this->endp << " > " << this->length << endl; } private: int startp; int endp; int size; Node *data; }; int main() { FixedQueue q(7); cout << "固定隊列已創建: " << q.length << endl; Node* n = q.getNode(); n->data = "111111111111111111"; Node* n1 = q.getNode(); n1->data = "2222222222"; Node* n2 = q.getNode(); n2->data = "33333333333333"; Node* n3 = q.getNode(); n3->data = "44444444444444444444"; Node* n4 = q.getNode(); n4->data = "555555555555555"; Node* n5 = q.getNode(); n5->data = "666666666666666666666666"; Node* n6 = q.getNode(); n6->data = "77777777777777"; Node* n7 = q.getNode(); // 出隊列 while(!q.empty()) { cout << q.pop()->data << endl; } q.print(); return 0; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM