Deque (Double-ended Queue)
Deque Operations in C++
IntermediateTopic: STL Containers Programs
C++ Deque (Double-ended Queue) Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <deque>
using namespace std;
int main() {
// Create deque
deque<int> dq;
// Add elements at both ends
dq.push_back(10);
dq.push_back(20);
dq.push_back(30);
dq.push_front(5);
dq.push_front(1);
cout << "Deque elements: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
cout << "Front: " << dq.front() << endl;
cout << "Back: " << dq.back() << endl;
cout << "Size: " << dq.size() << endl;
// Access elements by index
cout << "Element at index 2: " << dq[2] << endl;
cout << "Element at index 2 (at): " << dq.at(2) << endl;
// Remove from front
dq.pop_front();
cout << "\nAfter pop_front: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
// Remove from back
dq.pop_back();
cout << "After pop_back: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
// Insert at specific position
dq.insert(dq.begin() + 1, 15);
cout << "\nAfter inserting 15 at index 1: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
// Erase element
dq.erase(dq.begin() + 1);
cout << "After erasing element at index 1: ";
for (int num : dq) {
cout << num << " ";
}
cout << endl;
return 0;
}Output
Deque elements: 1 5 10 20 30 Front: 1 Back: 30 Size: 5 Element at index 2: 10 Element at index 2 (at): 10 After pop_front: 5 10 20 30 After pop_back: 5 10 20 After inserting 15 at index 1: 5 15 10 20 After erasing element at index 1: 5 10 20
Understanding Deque (Double-ended Queue)
Deque (double-ended queue) allows insertion and deletion at both ends efficiently. It provides random access like vectors but with efficient front operations. Operations: push_front(), push_back(), pop_front(), pop_back(), front(), back(), at(), []. Deque is implemented as a collection of memory blocks, providing O(1) operations at both ends and O(n) for middle insertions. Useful when you need both stack and queue functionality.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.