C++STL標準庫——雙端隊列deque
其實deque的最大特點就是雙端,其可以實現隊首隊尾都插入的功能
對比各種stl容器的存取難度
- vector:只能插入在隊首,但是提供下標訪問方式。⭐️⭐️⭐️
- stack:不支持下標訪問,存入只能存進棧頂,取出最後一個必須一個一個pop。⭐️
- queue:只能插入進隊首,不支持下標⭐️⭐️
- array:類似數組(幾乎就是),支持下標,可在任何地方插入⭐️⭐️⭐️⭐️⭐️
- deque:支持任意地方插入(insert),不支持下標,可在隊首隊尾插入⭐️⭐️⭐️⭐️
從列表中可見deque的存取效率非常高,注:個人認爲
用法
方法 | 含義 |
---|---|
deque | 構造函數 |
push_back | 在當前的最後一個元素之後 ,在 deque 容器的末尾添加一個新元素 |
push_front | 在 deque 容器的開始位置插入一個新的元素,位於當前的第一個元素之前 |
pop_back | 刪除 deque 容器中的最後一個元素,有效地將容器大小減少一個 |
pop_front | 刪除 deque 容器中的第一個元素,有效地減小其大小 |
emplace_front | 在 deque 的開頭插入一個新的元素,就在其當前的第一個元素之前 |
emplace_back | 在 deque 的末尾插入一個新的元素,緊跟在當前的最後一個元素之後 |
實例:
#include <iostream>
#include <deque>
int main ()
{
unsigned int i;
// constructors used in the same order as described above:
std::deque<int> first; // empty deque of ints
std::deque<int> second (4,100); // four ints with value 100
std::deque<int> third (second.begin(),second.end()); // iterating through second
std::deque<int> fourth (third); // a copy of third
// the iterator constructor can be used to copy arrays:
int myints[] = {16,2,77,29};
std::deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
std::cout << "The contents of fifth are:";
for (std::deque<int>::iterator it = fifth.begin(); it!=fifth.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
OUT:
The contents of fifth are: 16 2 77 29
實例2:
#include <iostream>
#include <deque>
int main ()
{
std::deque<int> mydeque;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
mydeque.push_back (myint);
} while (myint);
std::cout << "mydeque stores " << (int) mydeque.size() << " numbers.\n";
return 0;
}
OUT:
Please enter some integers (enter 0 to end):1 2 3 4 5 0
mydeque stores 6 numbers.