list::erase() method

Lists are sequence containers available in the C++ Standard Library. They allow non-contiguous memory allocation. List containers are implemented as doubly-linked lists. Compared to other sequence containers (eg: arrays, vectors etc.), lists have a better performance when it comes to inserting, moving or deleting elements. The list::erase() is a method available in the STL which removes either a single element or a range of elements.

Syntax:

list_name.erase(iterator_position); //single element
list_name.erase(iterator_first, iterator_last); //range of elements from [first,last)

Parameters: The list::erase() method accepts various parameters:
•Position of the element to be deleted (iterator)
•Iterators specifying a range of elements (first, last)
Return value: An iterator pointing to the element that followed the last element erased.

Example of list::erase() method

#include <iostream>
#include <list>
#include <vector>

using namespace std;

void print_list(list<int> L)
{
    for( list<int>::iterator it = L.begin(); it != L.end(); ++it)
    {
        cout<<*it<<" <--> ";
    }
    cout<<"NULL"<<endl;
}

int main()
{
    list<int> new_list;

    for(int i = 1; i <= 5; i++)
    {
        new_list.push_back(i);
    }

    print_list(new_list);

    list<int>::iterator it = new_list.begin();
    it++; it++; it++; //it points to 4

    new_list.erase(it);

    print_list(new_list);

    list<int>::iterator it1 = new_list.begin();
    list<int>::iterator it2 = new_list.begin();
    it2++;it2++; //it2 points to 3

    new_list.erase(it1,it2);

    print_list(new_list);
    
    return 0;
}

Output:

1 <--> 2 <--> 3 <--> 4 <--> 5 <--> NULL
1 <--> 2 <--> 3 <--> 5 <--> NULL
3 <--> 5 <--> NULL

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top