1.deque簡介
queue和stack類似,是STL中的容器適配器,它們並不是容器,而是基於其他容器實現。那麼什麼叫容器適配器呢,大家可以想一想電源適配器,沒錯就是下面這個:
它能直接給手機充電嗎?當然不能,那是它可以將電源轉化爲手機能夠適應的電壓。容器這裏就相當於電源,容器適配器對容器的接口進行封裝,以達到我們需要的要求。
queue的原理和操作十分簡單,即先進先出原則,即只能從隊列開頭刪除元素,只能從隊列末尾刪除元素,默認是基於deque(雙端隊列)實現的。使用時需要包含頭文件<queue>。
既然它默認是基於deque實現,那麼很容易想到,queue能實現的操作deque都能實現,事實也是如此。你可以會有疑問,既然如此,那爲什麼我們要用queue,而不是直接使用deque?在很多情況下,我們使用queue,就是爲了告訴自己或別人,這是一個隊列,防止熊孩子們的誤操作,把多餘的接口刪除,防止不必要的錯誤。就如同const關鍵字,其存在意義就是爲了防止數據被更改。
deque不提供迭代器,不提供隨機訪問。
2.構造
較爲簡單,直接看官方文檔的例子:
// constructing queues
#include <iostream> // std::cout
#include <deque> // std::deque
#include <list> // std::list
#include <queue> // std::queue
int main ()
{
std::deque<int> mydeck (3,100); // deque with 3 elements
std::list<int> mylist (2,200); // list with 2 elements
std::queue<int> first; // empty queue
std::queue<int> second (mydeck); // queue initialized to copy of deque
std::queue<int,std::list<int> > third; // empty queue with list as underlying container
std::queue<int,std::list<int> > fourth (mylist);
std::cout << "size of first: " << first.size() << '\n';
std::cout << "size of second: " << second.size() << '\n';
std::cout << "size of third: " << third.size() << '\n';
std::cout << "size of fourth: " << fourth.size() << '\n';
return 0;
}
運行結果:
size of first: 0 size of second: 3 size of third: 0 size of fourth: 2 |
3.成員函數
empty | 判讀隊列是否爲空,若爲空返回ture,否則返回false |
size | 返回隊列大小,返回值類型爲無符號整型 |
front | 返回隊列第一個元素 |
back | 返回隊列最後一個元素 |
push | 向隊列末尾插入元素 |
emplace | 向隊列末尾插入元素,c++11新特性,效率比push高 |
pop | 刪除第一個元素 |
swap | 交換隊列 |
4.非成員函數
1.swap(queue1,queue2)交換兩個隊列,成員函數裏也有swap這個函數,使用方法爲queue1.swap(queue2)
2.重載了==,!=,<,>,<=,>= 比較關係符