2022-8-30C++实现动态队列

队列是一种数据结构,用链表和数组都可以实现,队列的特点就是先放入队列的数据先出队列。不过看到话题标签有Redis,猜测题主想问的应该是现在很广泛使用的消息队列(MQ)。这里的消息不只是简单的文本信息,也可以是序列化后的对象。其核心作用都是先将消息数据通过系统接口按顺序放入队列(暂存于内存),需要时再按放入的顺序依次取出以作后续处理。

源代码:

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
class my_Queue{
private:
    int* myqueue;   //存放队列中数据的数组
    int maxsize; //队列的最大空间
    int front;     //队头
    int tail;     //队尾
    int num;     //队列中元素个数
    //int *head;    //头指针
    //int *low;     //尾指针

public:
    my_Queue(int max_size):maxsize(max_size) //有参构造,初始化队列
    {
       myqueue= new int[max_size];
       num=0;
       this->front=0;
       //head=myqueue+front;
       tail=0;
       //low=myqueue;
    }
    //拷贝构造函数
    my_Queue( const my_Queue& other)
    {
        //计算原空间尺寸
        int len =other.num;
        int size=other.maxsize;
        this->myqueue=new int[size];
        memcpy(this->myqueue,other.myqueue,len*sizeof(int));
        //this->head=other.head;
        //this->low=other.low;
    }
    //判空
    int empty()
    {
        return (num == 0)?1:0;
    }

    //判满
    int full()
    {
        return (num == maxsize)?1:0;
    }
    //入队
    void push_queue(int data)
    {
        if(num>maxsize){
            greater();
        }

            myqueue[tail++]=data;
            num++;
            //low++;

    }
    //队列增加
    void greater()
    {
        //int size=num+1;
        int *temp=new int[2*num];
        //将原空间数据放到新申请的空间里
        memcpy(temp,this->myqueue,num*sizeof(int));
       //释放原来数组内存
        delete []myqueue;

        myqueue=temp;

        //head=myqueue;
        //low=myqueue+num+1;
    }
    //出队
    void pop_queue()
    {
        if(num > 0)
        {
            front++; //队头前移
//            head++;
            --num; //数量减1
        }
        else
        {
            cout<<"队列内无成员,无法出队"<<endl;
        }
    }
    //队列大小
    int size()
    {
        return num;
    }

    int my_front() //显示成员信息
    {
        return myqueue[front];
    }
};

int main()
{


        //int temp[] = { 1,2,3,6,5,4,8,5,2 };
        my_Queue que(20);
        for (int i = 1; i <=30; i++)
        {
            que.push_queue(i);
        }

        while (que.empty() != 1)
        {
            cout << que.my_front() <<" "<<endl;
            que.pop_queue();
        }

        return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值