Open In App

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

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

In C++, Lists are sequence containers that allow non-contiguous memory allocation. In this article, we will learn how to remove an element from a list in C++.

Example

Input: 
myList = {100, 78, 120, 12, 56, 78, 78}
target = 78

Output:
// Removed element 78 from the list
{ 100, 120, 12, 56}

Remove an Element from a List in C++

To remove all occurrences of an element from a list in C++, we can use the remove() member function provided by the list class in the STL. This function removes all elements with a certain value from the list.

C++ Program to Remove an Element from a List

The following program illustrates how we can use the list::remove() function to remove an element from a list:

C++
// C++ Program to illustrate how to remove all
// occurrences of an element from a list
#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Initializing a list
    list<int> myList = { 1, 2, 3, 3, 4, 5 };

    // element to remove
    int target = 3;
    // using remove() to delete all occurrences of the
    // element
    myList.remove(target);

    // printing the list after removal
    cout << "The list after removing all occurrences of "
            "the element "
         << target << " is: ";
    for (int val : myList)
        cout << val << " ";

    return 0;
}

Output
The list after removing all occurrences of the element 3 is: 1 2 4 5 

Time complexity: O(N)
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads