Erase Range of Elements From List Using Iterators in C++ STL
Last Updated :
29 Dec, 2022
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++
#include <bits/stdc++.h>
using namespace std;
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;
}
void solve(list< int >& li, int key1, int key2)
{
list< int >::iterator it1;
list< int >::iterator it2;
cout << "Before Deletion: " << endl;
cout << "Size of List: " << li.size() << endl;
print(li);
it1 = find(li.begin(), li.end(), key1);
it2 = find(li.begin(), li.end(), key2);
it2++;
li.erase(it1, it2);
cout << "\nAfter Deletion: " << endl;
cout << "Size of List: " << li.size() << endl;
print(li);
}
int main()
{
list< int > li = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int key1 = 4, key2 = 7;
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...