當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Queue和Deque的區別用法及代碼示例

隊列: 隊列是一種線性數據結構,遵循先進先出 (FIFO) 順序執行操作。它是一種容器適配器,其中元素被插入容器的一端並從另一端刪除。

函數:

  • empty() :測試隊列是否為空。
  • size() :返回無符號整數,隊列的大小。
  • queue::front() and queue::back() : front() 函數返回對隊列中第一個元素或最舊元素的引用。 back() 函數返回對隊列的最後一個或最新元素的引用。
  • push(k) and pop() : push() 函數將元素‘k’ 添加到隊列末尾。 pop() 函數從隊列開頭刪除元素,並將其大小減少 1。
  • swap():交換相同類型的兩個不同隊列的元素,但大小可能相同也可能不同。
  • emplace() :用於在隊列末尾插入新元素。

用法:

queue <data_type> q

下麵的程序來說明這一點:

C++


// C++ program to demonstrate the
// working of queue
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
    // Declare a queue
    queue<int> q;
    // Insert elements in the queue
    q.push(10);
    q.push(5);
    q.push(15);
    q.push(1);
    // Delete elements from the queue
    q.pop();
    q.pop();
    cout << "Elements in Queue are: ";
    // Print the element stored
    // in queue
    while (!q.empty()) {
        cout << q.front() << ' ';
        // Pop the front element
        q.pop();
    }
    return 0;
}
輸出:
Elements in Queue are: 15 1

雙端隊列: 雙端隊列是一個序列容器具有兩端伸縮的能力。它是一個模板標準模板庫或STLC++是。它類似於向量但對於元素的插入和刪除效率更高。連續存儲分配雙端隊列中的情況可能無法像向量中那樣得到保證。

函數:

  • max_size() :返回雙端隊列可以包含的最大元素數。
  • push_back()push_front() :push_front( ) 將元素從前麵推入雙端隊列,push_back( ) 從後麵將元素推入雙端隊列。
  • pop_front() and pop_back() : pop_front() 函數用於從雙端隊列的前麵彈出元素,pop_back( ) 函數用於從雙端隊列的後麵彈出元素。
  • clear()erase() :clear 用於從雙端隊列中刪除所有元素,erase 用於刪除某些指定元素。
  • insert() :通過在指定位置插入元素來增加容器邊長。
  • resize():根據要求更改元素容器的大小。
  • rbegin()rend() :rbegin() 指向雙端隊列的最後一個元素,而 rend 指向雙端隊列開頭之前的位置。
  • at() and swap() : at() 指向參數中給出的元素的位置,swap( ) 用於兩個雙端隊列的兩個交換元素。
  • emplace_front() and emplace_back() :這兩個函數分別用於在雙端隊列的開頭和結尾處向容器中插入新元素。

用法:

deque<data_type> dq

下麵的程序來說明這一點:

C++


// C++ program to demonstrate the
// working of deque
#include <bits/stdc++.h>
using namespace std;
// Driver Code
int main()
{
    // Declare a deque
    deque<int> dq;
    // Insert element in the front
    dq.push_front(10);
    dq.push_front(5);
    dq.push_front(3);
    // Delete elements from the front
    dq.pop_front();
    dq.pop_front();
    // Insert elements in the back
    dq.push_back(1);
    dq.push_back(50);
    dq.push_back(2);
    // Delete elements from the back
    dq.pop_back();
    dq.pop_back();
    cout << "Elements in deque are: ";
    // Print the element stored
    // in deque
    while (!dq.empty()) {
        cout << " " << dq.front();
        dq.pop_front();
    }
    return 0;
}
輸出:
Elements in deque are:  10 1

下麵是隊列和雙端隊列之間的表格差異:

編號

Queue

Deque

1 隻能通過後端插入。 可以通過兩端插入。
2 隻能通過前端刪除元素。 可以通過兩端刪除元素。
3 無法通過迭代器訪問元素。 可以通過迭代器訪問元素。
4 作為容器適配器實現。 通常作為某種形式的動態數組來實現。
5 堆棧不能使用隊列來實現。 堆棧可以使用雙端隊列來實現。


相關用法


注:本文由純淨天空篩選整理自aktmishra143大神的英文原創作品 Difference between Queue and Deque in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。