在數據結構中還有一種很常見的隊列叫做雙端隊列,我們在上一篇博客《C++ STL學習——queue》中講到的隊列queue是一種最標准的隊列,只能在尾部插入數據,在頭部刪除數據。而今天我們講到的deque分別可以在兩端進行插入與刪除,可以說用起來更加的靈活。
(1)創建一個deque
dequedeque1; deque deque2(deque1); deque deque3(10); deque deque4(10,0);
deque1.push_back(1); deque1.push_back(2); deque1.push_back(3); deque1.push_back(4); PrintDeque(deque1);
(3)deque頭部插入數據
deque1.push_front(5); deque1.push_front(6); PrintDeque(deque1);
cout << "頭部元素為:" << deque1.front() << endl; cout << "尾部元素為:" << deque1.back() << endl; cout << "某位置的元素為:" << deque1.at(2) << endl; cout << "某位置的元素為:" << deque1[2] << endl;
(5)使用迭代器在某位置插入元素
// 使用迭代器插入或刪除元素 deque::iterator iterInsert = deque1.begin(); iterInsert = iterInsert + 2; deque1.insert(iterInsert, 99); PrintDeque(deque1);
(6)使用迭代器在某位置刪除元素
deque::iterator iterErase = deque1.begin(); iterErase = iterErase + 2; deque1.erase(iterErase); PrintDeque(deque1);
(7)size(), max_size()
cout << "deque1.size = " << deque1.size() << endl; cout << "deque1.max_size = " << deque1.max_size() << endl;
(8)頭部、尾部刪除元素
deque1.pop_back(); PrintDeque(deque1); deque1.pop_front(); PrintDeque(deque1);
// 交換兩個deque dequedequeSwap; dequeSwap.push_back(11); dequeSwap.push_back(22); dequeSwap.push_back(33); cout << "deque1:" ; PrintDeque(deque1); cout << "dequeSwap:"; PrintDeque(dequeSwap); deque1.swap(dequeSwap); cout << "deque1:" ; PrintDeque(deque1); cout << "dequeSwap:"; PrintDeque(dequeSwap);
(10)判斷deque是否為空
cout << "deque是否為空:" << deque1.empty() << endl; deque1.clear(); cout << "deque是否為空:" << deque1.empty() << endl; PrintDeque(deque1);
(11)迭代器打印deque
void PrintDeque(dequepDeque) { cout << "deque元素為:"; deque ::iterator dequeIter; for (dequeIter = pDeque.begin(); dequeIter != pDeque.end(); dequeIter++) { cout << *dequeIter << " "; } cout << endl; }