zoukankan      html  css  js  c++  java
  • 算法笔记--标准模板库STL--queue

    queue的常见用法

    queue是队列,在STL主要实现了一个先进先出的容器

    头文件

    #include<queue>
    using namespace std;
    

    queue的定义

    queue<typename> name;
    

    queue 容器内的元素访问

    由于队列queue本身就是一种先进先出的限制性数据结构,因此在STL中只能通过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 压入队列
        }
        printf("%d %d
    ", q.front(), q.back());	// 结果: 1 5
        return 0;
    }
    

    queue常用函数

    push( )

    push(x)将x进行入队,时间复杂度为O(1)

    front( ) | back( )

    分别用以获得队首和队尾元素,时间复杂度为O(1)

    pop( )

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

    #include<stdio.h>
    #include<queue>
    using namespace std;
    
    int main(){
        queue<int> q;
        for(int i = 1; i <= 5; i++){
            q.push(i); // 将i 压入队列
        }
        for(int i = 0; i < 3; i++){
            q.pop();		// 三次出队,分别是1 2 3 
        }
        printf("%d %d
    ", q.front(), q.back()); // 4 5
        return 0;
    }
    
    

    empty( )

    检测queue是否为空,返回true为空,false为非空,时间复杂度为O(1)

    #include<stdio.h>
    #include<queue>
    using namespace std;
    
    int main(){
        queue<int> q;
        q.empty() ? printf("Empty
    ") : printf("No Empty");
        for(int i = 1; i <= 5; i++){
            q.push(i); // 将i 压入队列
        }
        for(int i = 0; i < 3; i++){
            q.pop();
        }
        printf("%d %d
    ", q.front(), q.back()); // 4 5
        q.empty() ? printf("Empty
    ") : printf("No Empty");
        return 0;
    }
    

    size( )

    返回queue内元素个数,时间复杂度为O(1)

    #include<stdio.h>
    #include<queue>
    using namespace std;
    
    int main(){
        queue<int> q;
        for(int i = 1; i <= 5; i++){
            q.push(i); // 将i 压入队列
        } 
        printf("%d", q.size()); // 结果: 5
        return 0;
    }
    
    

    queue的常见用途

    • 当需要实现广度优先搜索时,可以不用自己手动实现一个队列,而是用queue作为代替,
      以提高程序的准确性。
    • 另外有一点注意的是,使用front()pop()函数前,必须empty()判断队列是否为空,
      否则可能因为队空而出现错误。

    Write by Gqq

  • 相关阅读:
    [USACO09Open] Tower of Hay 干草塔
    [HNOI2004]打鼹鼠
    BZOJ1222[HNOI 2001]产品加工
    BZOJ1270[BJWC2008]雷涛的小猫
    NOIP2018出征策
    解析·NOIP·冷门 CLZ最小环
    CCF-NOIP-2018 提高组(复赛) 模拟试题(九)(2018 CSYZ长沙一中)
    [脚本无敌1]图片批量处理(matlab)
    用Matlab解《2013年数据建模比赛》图像碎片拼接题
    火灾检测-fire,fire
  • 原文地址:https://www.cnblogs.com/zgqcn/p/12586289.html
Copyright © 2011-2022 走看看