Open In App

How to Add Element at Front of a Deque in C++?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a deque is a vector like data structure that allows users to add and remove elements from both the front and the back ends. In this article, we will learn how to add an element at the beginning of a deque in C++.

Example:

Input:
myDeque: {1, 2, 3}

Output:
myDeque = {11, 1, 2, 3}

Add an Element at the Beginning of a Deque in C++

To add an element at the beginning of a std::deque in C++, we can use the deque::push_front () method. This method takes the value to be inserted as an argument and inserts it to the beginning of the deque.

Syntax:

dq_name.push_front(value);

C++ Program to Add an Element at the Beginning of a Deque

The following program illustrates how we can add an element at the beginning of a deque in C++:

C++
// C++ Program to illustrates how we can add an element at
// the beginning of a deque
#include <deque>
#include <iostream>
using namespace std;

int main()
{

    // Initializing a deque
    deque<int> dq = { 10, 20, 30, 40, 50 };

    // Print the Original Deque
    cout << "Original Deque: ";
    for (int ele : dq) {
        cout << ele << " ";
    }
    cout << endl;

    // Element to add at the beginning
    int element = 5;

    // Adding element at the beginning of the deque
    dq.push_front(element);

    // Print the Updated Deque
    cout << "Updated Deque: ";
    for (int ele : dq) {
        cout << ele << " ";
    }
    return 0;
}

Output
Original Deque: 10 20 30 40 50 
Updated Deque: 5 10 20 30 40 50 

Time Complexity: O(1)
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads