How to Remove an Element from a List in C++?
In C++, the STL provides a std::list
container that represents a doubly linked list to store the sequential data in non-contiguous memory locations. In this article, we will learn how to remove an element from a list in C++.
Example:
Input: myList = {1, 2, 3, 4, 5, 6, 7, 8} Target = 5 Output: // removed element 5 from the list myList = {1, 2, 3, 4, 6, 7, 8}
Removing an Element from a List in C++
In C++, the std::list
class template provides a member function std::list::remove()
that can be used to remove a specific element from a list. The function accepts the value of the element to be removed and then removes all elements that compare equal to the specified value from the list.
Syntax of std::list::remove
list_name.remove(value_to_remove);
C++ Program to Remove an Element from a List
The below example demonstrates the use of the std::list::remove() function to remove an element from a std::list in C++ STL.
// C++ program to illustrate how to remove an element from a
// list
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Creating a list of integers
list<int> nums = { 10, 20, 30, 40, 50 };
// Element to remove
int target = 50;
// Print the initial list
cout << "List before removal: ";
for (auto num : nums) {
cout << num << " ";
}
cout << endl;
// Removing the element from the list
nums.remove(target);
// Printing the list after removal
cout << "List after removal : ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
Output
List before removal: 10 20 30 40 50 List after removal : 10 20 30 40
Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(1)
Contact Us