STL之队列的应用

版权声明:Copyright © 钟波 https://blog.csdn.net/gzu_zb/article/details/89886189

Queue队列容器:

1)容器适配器,遵循先进先出(FIFO)数据结构。

2)头文件:#include <queue>

3)常用函数:
queue<int>q;

q.empty()// 如果队列为空返回true,否则返回false  
q.size() // 返回队列中元素的个数  
q.pop()  //删除队列首元素但不返回其值  
q.front()  // 返回队首元素的值,但不删除该元素  
q.push(X) //在队尾压入新元素 ,X为要压入的元素
q.back() //返回队列尾元素的值,但不删除该元素

例子:

#include<queue>
#include<iostream>
using namespace std;

int main() {
    queue<int>Q;
    int a[] = { 3,5,17,9,30,15,2,4 };
    int l = sizeof(a) / sizeof(int);

    for (int i = 0; i < l; i++) {
        Q.push(a[i]);//入队
    }

    cout << Q.back() << endl;//输出队尾元素

    cout << Q.front() << endl;//输出队首元素

    cout << Q.size() << endl;//输出队列的长度

    Q.pop();//出队,注意此函数并不返回任何值

    //输出队列中的所有元素
    while (!Q.empty) {
        cout << Q.front() << " ";
        Q.pop();
    }

    //清空队列
    while (!Q.empty) {
        Q.pop();
    }
    return 0;
}

数据结构实现:

//队列:队首出,队尾进(先进先出表)
#include<iostream>
using namespace std;

const int MAXN = 1000 + 5;

struct Queue {
    int *queue;
    int front;
    int rear;
    int len;
};

//初始化队列
void InitQueue(Queue& Q) {
    Q.queue = new int[MAXN];
    Q.front = Q.rear = 0;
    Q.len = 0;
}

//入队
void InsertQueue(Queue& Q, int item) {
    Q.rear = (Q.rear + 1) % MAXN;
    Q.queue[Q.rear] = item;
    Q.len++;
}

//清空队列
void ClearQueue(Queue& Q) {
    if (Q.queue != NULL) delete[] Q.queue;
    Q.front = Q.rear = 0;
    Q.queue = NULL;
    Q.len = 0;
}

//出队
void PopQueue(Queue& Q) {
    Q.front = (Q.front + 1) % MAXN;
    Q.len--;
}

//求队首元素
int PeekQueue(Queue Q) {
    return Q.queue[(Q.front + 1) % MAXN];
}

//判断队列是否为空
bool EmptyQueue(Queue Q) {
    return Q.front == Q.rear;
}

int main() {
    Queue Q;
    InitQueue(Q);

    int a[] = { 2,4,5,6,7,9,10,3 };
    int l = sizeof(a) / sizeof(int);
    for (int i = 0; i < l; i++) {
        InsertQueue(Q, a[i]);
    }

    cout << Q.len << endl;//输出队列的长度

    cout << PeekQueue(Q) << endl;//查看队首元素

    PopQueue(Q);//删除队首元素
    PopQueue(Q);//删除队首元素

    //依次输出队列的元素
    while (!EmptyQueue(Q)) {
        cout << PeekQueue(Q) << " ";
        PopQueue(Q);
    }

    ClearQueue(Q);//清空队列
    return 0;
}

猜你喜欢

转载自blog.csdn.net/gzu_zb/article/details/89886189
今日推荐