3.Queues(队列)

C++队列详解

一.概述

C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构,与stack刚好相反

二.常用API

back()返回最后一个元素
empty()如果队列空则返回真
front()返回第一个元素
pop()删除第一个元素
push()在末尾加入一个元素
size()返回队列中元素的个数

三.示例Demo

#include <iostream>
#include <stdlib.h>
#include <queue>

using namespace std;
#pragma warning(disable:4996)



struct Teacher {
    char name[20];
    int age;
};


void printQueue(queue<Teacher *> &v) {
    
    while (!v.empty())
    {
        Teacher *teacher = v.front();
        cout << "Teacher, name is: " << teacher->name << ", age is: " << teacher->age << endl;
        cout << "current remain num is: " << v.size() << endl;
        v.pop();
    }

}


int main() {
    
    
    Teacher *t1 = (Teacher *)malloc(sizeof(Teacher));
    Teacher *t2 = (Teacher *)malloc(sizeof(Teacher));
    Teacher *t3 = (Teacher *)malloc(sizeof(Teacher));

    strcpy(t1->name,"jack");
    t1->age = 11;
    strcpy(t2->name,"mike");
    t2->age = 22;
    strcpy(t3->name,"tom");
    t3->age = 33;


    queue<Teacher *> v;
    v.push(t1);
    v.push(t2);
    v.push(t3);

    printQueue(v);

    free(t1);
    free(t2);
    free(t3);


    system("pause");

    return 0;
}

运行结果:

Teacher, name is: jack, age is: 11
current remain num is: 3
Teacher, name is: mike, age is: 22
current remain num is: 2
Teacher, name is: tom, age is: 33
current remain num is: 1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值