Open In App

Erase Range of Elements From List Using Iterators in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites:

A list is a type of container which requires the same properties as a doubly linked list. We can insert elements from either side of the list, but accessing elements with an index is not possible in the list. So, removing elements from the list is not an easy task. But, we have a method to remove multiple elements from a list using an iterator.

Erasing multiple elements using an iterator 

Iterators are used for pointing out the memory address of elements in a container. We can use iterators to remove a range of elements from the list.

Syntax

list_name.erase(it1, it2);

Parameters:

  • it1 = iterator pointing to the first element of the range
  • it2 = iterator pointing to the last element of the range

Example:

l={1,2,3,4,5,6,7,8,9};

// remove elements from the list
l.erase(4,7);

// Now values are {1,2,3,8,9} 

Time Complexity:

Time Complexity: O(N)

Auxiliary Space: O(1)

Below is the implementation of the above example:

C++




// C++ Program to implement to
// Remove range of elements using
// Iterators
#include <bits/stdc++.h>
using namespace std;
  
// Function to print elements From
// the list While iterating
void print(list<int>& li)
{
    auto it = li.begin();
  
    if (it == li.end()) {
        cout << "List is Empty" << endl;
    }
  
    for (it; it != li.end(); it++) {
        cout << *it << " ";
    }
  
    cout << endl;
}
  
// Function to delete key
// element from the list
void solve(list<int>& li, int key1, int key2)
{
  
    list<int>::iterator it1;
    list<int>::iterator it2;
  
    // Before Deletion
    cout << "Before Deletion: " << endl;
  
    cout << "Size of List: " << li.size() << endl;
  
    print(li);
  
    // Finding key elements from the list
    it1 = find(li.begin(), li.end(), key1);
    it2 = find(li.begin(), li.end(), key2);
    it2++;
  
    // Deleting the range from the list
    li.erase(it1, it2);
  
    // After Deletion
    cout << "\nAfter Deletion: " << endl;
    cout << "Size of List: " << li.size() << endl;
  
    print(li);
}
  
// Driver Code
int main()
{
    // List created
    list<int> li = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  
    int key1 = 4, key2 = 7;
  
    // Calling function to remove eleents from the list
    solve(li, key1, key2);
  
    return 0;
}


Output

Before Deletion: 
Size of List: 9
1 2 3 4 5 6 7 8 9 

After Deletion: 
Size of List: 5
1 2 3 8 9 


Last Updated : 29 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads