Understanding deque

Understanding deque in C++

What is deque?

deque (double-ended queue) is a sequence container in the C++ Standard Library that allows efficient insertion and deletion of elements at both the front and the back. It provides similar functionalities to vector but with the added flexibility of efficiently managing elements at both ends.

Why Use deque?

  • Bidirectional Access: Allows insertion and deletion at both the front and back.

  • Dynamic Size: Can grow and shrink dynamically.

  • Random Access: Provides random access to elements, similar to vector.

Syntax

Here's the basic syntax for creating a deque:

#include <deque> using namespace std; deque<ElementType> dequeName;
  • ElementType: The type of elements stored in the deque.

  • dequeName: The name of the deque object.

Common deque Functions

push_back

Description: Adds an element to the end of the deque.

Syntax:

void push_back(const value_type& value);

Example:

#include <iostream> #include <deque> using namespace std; int main() { deque<int> myDeque; myDeque.push_back(10); myDeque.push_back(20); myDeque.push_back(30); for (const int& val : myDeque) { cout << val << " "; } cout << endl; return 0; }

push_front

Description: Adds an element to the front of the deque.

Syntax:

Example:


pop_back

Description: Removes the last element from the deque.

Syntax:

Example:


pop_front

Description: Removes the first element from the deque.

Syntax:

Example:


front

Description: Accesses the first element of the deque.

Syntax:

Example:


back

Description: Accesses the last element of the deque.

Syntax:

Example:


empty

Description: Checks if the deque is empty.

Syntax:

Example:


size

Description: Returns the number of elements in the deque.

Syntax:

Example:

2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark