How to erase an element from a vector using erase() and reverse_iterator?
Last Updated :
10 Oct, 2019
Given a vector, the task is to erase an element from this vector using erase() and reverse_iterator.
Example:
Input: vector = {1, 4, 7, 10, 13, 16, 19}, element = 16
Output: 1 4 7 10 13 19
Input: vector = {99, 89, 79, 69, 59}, element = 89
Output: 99 79 69 59
Approach:
- Get the vector and the element to be deleted
- Initialize a reverse iterator on the vector
- Erase the required element with the help of base() and erase()
Reason for using base(): erase() returns a valid iterator to the new location of the element which follows the one, which was just erased, in a forward sense. So we can’t use the same process while using reverse iterators where we want to go in the reverse direction instead of forward. And also we can’t pass a reverse iterator as a parameter to erase() function or it will give a compilation error.
A reverse_iterator is just an iterator adaptor that reverses the direction of a given iterator. All operations on the reverse_iterator really occur on that underlying iterator. We can obtain that iterator using the reverse_iterator::base() function. Infact the relationship between itr.base() and itr is:
&*(reverse_iterator(itr))==&*(itr-1)
Below is the implementation of the above approach:
#include <iostream>
#include <vector>
using namespace std;
vector< int > delete_ele(vector< int > vec, int num)
{
vector< int >::reverse_iterator itr1;
for (itr1 = vec.rbegin(); itr1 < vec.rend(); itr1++) {
if (*itr1 == num) {
vec.erase((itr1 + 1).base());
}
}
return vec;
}
int main()
{
vector< int > vec = { 1, 4, 7, 10, 13, 16, 19 };
int num = 16;
vector< int >::iterator itr1;
cout << "Vector originally: \n" ;
for (itr1 = vec.begin(); itr1 < vec.end(); itr1++) {
cout << *itr1 << " " ;
}
cout << "\n\nElement to be deleted: "
<< num << "\n\n" ;
vec = delete_ele(vec, num);
vector< int >::iterator itr2;
cout << "Vector after deletion: \n" ;
for (itr2 = vec.begin(); itr2 < vec.end(); itr2++) {
cout << *itr2 << " " ;
}
return 0;
}
|
Output:
Vector originally:
1 4 7 10 13 16 19
Element to be deleted: 16
Vector after deletion:
1 4 7 10 13 19
Share your thoughts in the comments
Please Login to comment...