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; }
  • 相关阅读:
    linux内核中如何访问寄存器?
    uboot加载itb文件后提示"ERROR: new format image overwritten"如何处理?
    如何单独编译Linux内核源码中的驱动为可加载模块?
    openwrt如何打开linux内核的CONFIG_DEVMEM选项?
    openwrt的shell下如何访问寄存器的内容?
    linux系统错误码大全
    第 3 章 文本元素
    第 2 章 基本格式
    第 1 章 HTML5 概述
    第 20 章 项目实战--案例和关于[7]
  • 原文地址:https://www.cnblogs.com/hello-dummy/p/14700421.html
Copyright © 2011-2022 走看看