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
Deque
- .clear()
- Removes all elements from a given deque.
- .empty()
- Checks if a given deque container is empty.
- .insert()
- Inserts an element at a specified position in the deque.
- .push_back()
- Adds an element to the end of the deque.
- .rend()
- Returns a reverse iterator pointing to the element before the first element in the deque container.
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.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours