Open In App

How to Add an Element at the End of a Deque in C++?

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

In C++, a deque is a flexible data structure that supports the insertion and deletion of elements from both ends efficiently. In this article, we will learn how to add an element at the end of a deque in C++.

Example:

Input:
myDeque ={10,20,30,40}

Output:
// added element 50 at the end
myDeque ={10,20,30,40,50}

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

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

Syntax:

deque_name.push_back(value);

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

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

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

int main()
{
    // Initialize a deque with few elements
    deque<int> dq = { 10, 20, 30, 40 };

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

    // Declare the  element to add at the end of the deque
    int element = 50;

    // Add the element at the end of the deque using
    // push_back
    dq.push_back(element);

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

Output
Original Deque: 10 20 30 40 
Updated Deque: 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