C++STL標準庫——雙端隊列deque

C++STL標準庫——雙端隊列deque

其實deque的最大特點就是雙端,其可以實現隊首隊尾都插入的功能

對比各種stl容器的存取難度

  1. vector:只能插入在隊首,但是提供下標訪問方式。⭐️⭐️⭐️
  2. stack:不支持下標訪問,存入只能存進棧頂,取出最後一個必須一個一個pop。⭐️
  3. queue:只能插入進隊首,不支持下標⭐️⭐️
  4. array:類似數組(幾乎就是),支持下標,可在任何地方插入⭐️⭐️⭐️⭐️⭐️
  5. 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.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章