Open In App

How to Remove All Occurrences of an Element from Deque in C++?

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

In C++, a deque (double-ended queue) is a container that allows insertion and deletion at both its beginning and end. In this article, we will learn how to remove all occurrences of a specific element from a deque in C++.

Example:

Input: 
deque = {1, 2, 3, 4, 3, 2, 1}
element to remove = 2

Output: 
Updated deque is : 1 3 4 3 1

Remove All Occurrences of an Element from Deque in C++

To remove all occurrences of a specific element from a std::deque, we can use the combination of std::deque::erase() and std::remove() functions. The std::remove() algorithm can be used to reorder the elements that are equal to the specified value at the end of the container and then we use the std::erase() function to actually remove them.

C++ Program to Remove All Occurrences of a Specific Element from a Deque

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

C++
// C++ program to illustrate how to remove all occurences of
// a specific element from a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

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

    // Element to remove
    int toRemove = 2;

    // Removing the element
    auto newEnd = remove(dq.begin(), dq.end(), toRemove);
    dq.erase(newEnd, dq.end());

    // Printing the modified deque
    cout << "Deque after removal: ";
    for (int elem : dq) {
        cout << elem << " ";
    }
    cout << endl;

    return 0;
}

Output
Deque after removal: 1 3 4 3 1 

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