Open In App

How to Remove an Element from a Deque in C++?

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

In C++ STL, a container called deque (known as a double-ended queue) allows us to insert and delete elements at both its beginning and its end. In this article, we will learn how to remove a specific element from a deque in C++ STL.

Example:

Input: 
myDeque= {4, 2, 3, 5, 2}
Target = 4

Output: 
Deque After Removal of Target = 2 3 5 2

Erase a Specific Element from a Deque in C++

To remove a specific element from a deque in C++, we can use a combination of std::find() and the std::deque::erase() methods by finding the element first using the find() and then erasing it using the erase() function.

If the element is at either of the end, the std::deque::erase() function is optimized for the fast removal as well.

C++ Program to Remove a Specific Element from a Deque

The below example demonstrates how we can remove a specific element from a deque in C++ STL.

C++
// C++ program to demonstrate how we can remove a specific
// element from a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Initializing a deque
    deque<int> dq = { 4, 2, 3, 5, 2 };

    // Element to remove
    int Target = 4;

    // Removing the element
    auto it = find(dq.begin(), dq.end(), Target);
    if (it != dq.end()) {
        dq.erase(it);
    }
    else {
        cout << "Element not found in the deque." << endl;
    }

    // Printing the result

    cout << "Deque after removal: ";
    for (int elem : dq) {
        cout << elem << " ";
    }
    cout << endl;

    return 0;
}

Output
Deque after removal: 2 3 5 2 

Time Complexity: O(N), here N is the number of elements in the deque
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads