Sobes.tech
Junior — Middle

Can you explain what a deque (double-ended queue) is and how it works?

sobes.tech AI

Answer from AI

A double-ended queue (Deque) is a data structure that allows adding and removing elements from both ends: both from the front and the back.

Unlike a regular queue (FIFO), where elements are added at the back and removed from the front, a deque is more flexible and can function as a stack or a queue.

Example operations with Deque:

  • push_front — add an element to the front
  • push_back — add an element to the back
  • pop_front — remove an element from the front
  • pop_back — remove an element from the back

In C++, you can use the standard container std::deque to work with a deque:

#include <deque>
#include <iostream>

int main() {
    std::deque<int> d;
    d.push_back(1);    // add to the back
    d.push_front(2);   // add to the front

    std::cout << d.front() << " " << d.back() << std::endl; // 2 1

    d.pop_front();     // remove from the front
    std::cout << d.front() << std::endl; // 1

    return 0;
}