How to erase an element from a vector using erase() and reverse_iterator?
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:
// C++ program to delete an element of a vector // using erase() and reverse iterator. #include <iostream> #include <vector> using namespace std; // Function to delete element // 'num' from vector 'vec' vector< int > delete_ele(vector< int > vec, int num) { // initializing a reverse iterator vector< int >::reverse_iterator itr1; for (itr1 = vec.rbegin(); itr1 < vec.rend(); itr1++) { if (*itr1 == num) { // erasing element = 16 vec.erase((itr1 + 1).base()); } } return vec; } // Driver code int main() { vector< int > vec = { 1, 4, 7, 10, 13, 16, 19 }; // we want to delete element = 16 int num = 16; vector< int >::iterator itr1; cout << "Vector originally: \n" ; for (itr1 = vec.begin(); itr1 < vec.end(); itr1++) { // printing the original elements of vector cout << *itr1 << " " ; } cout << "\n\nElement to be deleted: " << num << "\n\n" ; // reinitializing vector 'vec' // after deleting 'num' // from the vector // and keeping other remaining // elements as they are vec = delete_ele(vec, num); vector< int >::iterator itr2; cout << "Vector after deletion: \n" ; for (itr2 = vec.begin(); itr2 < vec.end(); itr2++) { // printing the remaining elements of vector cout << *itr2 << " " ; } return 0; } // This code is contributed by supratik_mitra |
Vector originally: 1 4 7 10 13 16 19 Element to be deleted: 16 Vector after deletion: 1 4 7 10 13 19
Please Login to comment...