因为有需求,需要程序在内存大小保存不变来保存数据,但是数据的取用又是按队列的来操作,节约时间节约内存,但是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;
}
原文链接: https://www.cnblogs.com/hello-dummy/p/14700421.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/209836
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!