zoukankan      html  css  js  c++  java
  • 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; }
  • 相关阅读:
    20200713 T3 图论
    20200713 T1序列问题
    【题解】P1441 砝码称重
    【题解】P2858 [USACO06FEB]Treats for the Cows G/S
    【比赛】AISing Programming Contest 2019
    20200709 T3 城堡
    20200709 T2 括号
    20200709 T1 笔记
    20200628 T3 网络检查
    个人技术总结
  • 原文地址:https://www.cnblogs.com/hello-dummy/p/14700421.html
Copyright © 2011-2022 走看看