c-plus-plus
  1. c-plus-plus-deque

C++ STL Tutorial: Deque

In C++, deque (double-ended queue) is a container in the Standard Template Library (STL) that allows elements to be inserted and removed from both ends. It is similar to a vector, but has faster insertion and deletion of elements at both ends.

Syntax

#include<deque>

std::deque<data_type> deque_name;

Example

#include <iostream>
#include <deque>

using namespace std;

int main() {
    deque<int> dq;

    dq.push_back(1);
    dq.push_front(2);
    dq.push_back(3);

    for (int i : dq) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

Output

2 1 3

Explanation

In the above example, we have created a deque object called "dq" of integer type. We have inserted elements using the "push_back" and "push_front" methods. The "for" loop is then used to print the elements of the deque.

Use

Deques are used in scenarios where elements need to be inserted or removed from both ends of a container. They have constant time complexity for insertion and deletion of elements from both ends, making them suitable for use in algorithms that require such functionality.

Important Points

  • Deques allow insertion and deletion of elements at both ends.
  • Insertion and deletion of elements from both ends have constant time complexity.
  • Deques allow random access to elements through subscript operator [] and at() function.
  • Deques can also be resized dynamically.

Summary

Deques in C++ are a useful container in the STL that provide fast insertion and deletion of elements from both ends. They are suitable for scenarios where elements need to be frequently inserted or removed from both ends of a container. Additionally, they offer random access to elements and dynamic resizing.

Published on: