STL queue 常見用法詳解


《算法筆記》學習筆記

queue 常見用法詳解

queue翻譯為隊列,在STL中主要則是實現了一個先進先出的容器。

1. queue 的定義

//要使用queue,應先添加頭文件#include <queue>,並在頭文件下面加上"using namespace std;",即可使用。
//定義寫法
queue< typename > name;
//typename 可以是任意基本數據類型或容器

2. 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);  //push(i)用以將i壓入隊列,因此依次入隊 1 2 3 4 5
    }
    printf("%d %d\n", q.front(), q.back()); //輸出結果是1 5
    return 0;
}

3.queue實用函數實例解析

(1) push()

//push(x)將x進行入隊,時間復雜度為O(1),實例見"queue"容器內元素的訪問。

(2) front(), back()

//front()和back()可以分別獲得隊首元素和隊尾元素,時間復雜度為O(1),實例見"queue"容器內元素的訪問。
//使用front()前,必須用empty()判斷隊列是否為空

(3) pop()

//pop()令隊首元素出隊,時間復雜度為O(1)
//使用pop()前,必須用empty()判斷隊列是否為空
#include <stdio.h>
#include <queue>
using namespace std;
int main() {
    queue<int> q;
    for(int i = 1; i <= 5; i++) {
        q.push(i);  //依次入隊1 2 3 4 5
    }
    for(int i = 1; i <= 3; i++) {
        q.pop();    //出隊首元素三次(即依次出隊1 2 3)
    }
    printf("%d\n", q.front()));
    return 0;
}

(4) empty()

//empty()檢測queue是否為空,返回true則空,返回false則非空。時間復雜度為O(1)
#include <stdio.h>
#include <queue>
using namespace std;
int main() {
    queue<int> q;
    if(q.empty() == true) { //一開始隊列內沒有元素,所以是空
        printf("Empty\n");
    } else {
        printf("Not Empty\n");
    }
    q.push(1);
    if(q.empty() == true) { //在入隊"1"后,隊列非空
        printf("Empty\n");
    } else {
        printf("Not Empty\n");
    }
    return 0;
}

(5) size()

//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);  //push(i)用以將i壓入隊列
    }
    printf("%d\n", q.size());   //隊列中有5個元素
    return 0;
}

4. queue的常見用途

  • 需要實現廣度優先搜索時,可以不用自己手動實現一個隊列,而是用queue作為替代。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM