List remove() function in C++ STL


In this article we will be discussing the working, syntax and examples of remove() function in C++.

What is a List in STL

List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.

What is remove()

remove() is an inbuilt function in C++ STL which is declared in header file. remove() is used to remove any specific value/element from the list container. It takes the value which is passed as a parameter and removes all the elements with that value from the list container.The function calls destructor if the size of element removed is greater than the size of the list container.

Syntax

list_name.remove(const value_type& value);

This function accepts a value which is to be searched from the list container and to be removed.

Return Value

This function returns nothing, just removes element from the container.

Example

 Live Demo

/*
In the code below we are inserting elements to the list and then we will try to remove the elements from the list using their values. */
#include <bits/stdc++.h>
using namespace std;
int main(){
   //create a list
   list<int> myList;
   //insert elements to the List
   myList.push_back(1);
   myList.push_back(1);
   myList.push_back(3);
   myList.push_back(2);
   myList.push_back(5);
   //my list before removing elements
   cout<<"List before removing elements: ";
   for (auto i = myList.begin(); i!=myList.end(); i++){
      cout << *i << " ";
   }
   //deleting 1 2 and 3 from the list
   myList.remove(1);
   myList.remove(2);
   myList.remove(3);
   // List after removing elements
   cout << "\nList after removing elements: ";
   for (auto i = myList.begin(); i!= myList.end(); i++){
      cout << *i << " ";
   }
   return 0;
}

Output

If we run the above code then it will generate the following output

List before removing elements: 1 1 3 2 5
List after removing elements: 5

Updated on: 26-Feb-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements