234234234

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; }
复制代码

 

posted @   你若愿意,我一定去  阅读(2485)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2020-04-25 [蓝桥杯]错误票据
23423423423
点击右上角即可分享
微信分享提示