zoukankan      html  css  js  c++  java
  • C++标准模板库(STL)之Queue

    1、Queue的常用用法

    queue:队列,实现的一个先进先出的容器。

    1.1、queue的定义

    使用queue,首先要加头文件#include<queue>和using namespace std;

    queue<typename> name;
    queue<int> q;
    queue<double> q;
    queue<char> q;
    queue<Node> q;//Node是结构体

    1.2、queue容器元素的访问

    queue是一种先进先出的限制性数据结构。通过front()访问队首元素,通过back()来访问队尾元素。

    #include<stdio.h>
    #include<queue>
    
    using namespace std;
    
    int main()
    {
        queue<int> q;
        for(int i=1;i<=5;i++)
        {
            q.push(i);//依次将i入队,1,2,3,4,5
        }
        printf("%d %d
    ",q.front(),q.back());//输出结果1,5
        return 0;
    }
    View Code

    1.3、queue常用函数

    1.3.1、front(),back()

    获取队首,队尾元素,时间复杂度为O(1)

    1.3.2、pop()

    队首元素出队,时间复杂度为O(1)

    1.3.3、empty()

    检测queue是否为空,返回bool类型,true为空。

    1.3.4、size()

    返回queue内元素个数

    1.4、queue的用途

    当需要实现广度优先搜索的时候,可以使用queue代替。

    使用front()和back()的时候,必须判断队列是否为空,empty()。

    #include<stdio.h>
    #include<queue>
    
    using namespace std;
    
    int main()
    {
        queue<int> q;
        if(q.empty()==true)printf("Empty
    ");
        for(int i=1;i<=5;i++)
        {
            q.push(i);//依次将i入队,1,2,3,4,5
        }
        for(int i=1;i<3;i++)
        {
            q.pop();//出队首元素三次,1,2,3
        }
        printf("%d %d
    ",q.front(),q.back());//输出结果1,5
        return 0;
    }
    View Code

    2018-09-25 19:39:03

    @author:Foreordination

  • 相关阅读:
    拓扑排序
    Codeforces #503 C. Elections(贪心,逆向
    Codeforces #367 (Div. 2) D. Vasiliy's Multiset (trie 树)
    字典树
    最大子段和
    P1880 [NOI1995] 石子合并
    P1140 相似基因
    P1280 尼克的任务
    [BZOJ4064/Cerc2012]The Dragon and the knights
    [BZOJ4066]简单题
  • 原文地址:https://www.cnblogs.com/drq1/p/9699480.html
Copyright © 2011-2022 走看看