Deque
Anonymous contributor
Published Sep 25, 2024
Contribute to Docs
A deque (double-ended queue) in C++ is a sequence container that allows adding and removing elements from both the front and back efficiently. Unlike a vector, which only allows fast insertions and deletions at the back, a deque provides constant time complexity for insertions and deletions at both ends. This is useful for scenarios like implementing queues, stacks, or sliding window algorithms.
Syntax
std::deque<datatype> name;
datatype
: The type of elements the deque will hold (e.g., int, float, string, etc.).name
: The name of the deque.
Example
The following code inserts elements (13
& 8
) at the front and back and access them.
#include <deque>#include <iostream>int main() {std::deque<int> myDeque; // Declare a deque of integersmyDeque.push_back(13); // Insert element at the backmyDeque.push_front(8); // Insert element at the frontstd::cout << "Front: " << myDeque.front() << std::endl;std::cout << "Back: " << myDeque.back() << std::endl;return 0;}
The output of the above program will be:
Front: 8Back: 13
Equivalent Methods in Stack, Queue, and Deque
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.