C++ Program to remove items from a given vector

C++Server Side ProgrammingProgramming

Suppose we have a set of elements present inside a vector. We shall have to perform some remove operation using erase() function of vector class type to remove using indices, and finally display rest of elements. The erase function does not take the index directly. We shall have to pass its address by passing v.begin()+index, here v is the vector and v.begin() is the address of the first element (0th element). Now by adding index with it, it will move towards the element that is present at given index.

So, if the input is like v = [5,8,6,3,2,0,1,4] erase from indices 2, 6 and 5, then the output will be [5,8,3,2,0] because initially array was [5,8,6,3,2,0,1,4], now after removing element from index 2, it is [5,8,3,2,0,1,4], now the element at index 6 is 4, so after removing it, the array will be [5,8,6,3,2,0,1] and now the item at index 5 is 1, so after removing it, then array will be [5,8,3,2,0].

To solve this, we will follow these steps −

  • erase element at index 2 by v.erase(v.begin()+2)

  • erase element at index 6 by v.erase(v.begin()+6)

  • erase element at index 5 by v.erase(v.begin()+5)

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
   vector<int> v = {5,8,6,3,2,0,1,4};
   v.erase(v.begin()+2);
   v.erase(v.begin()+6);
   v.erase(v.begin()+5);
   for(int i = 0; i<v.size(); i++){
       cout << v[i] << " ";
   }
}

Input

{5,8,6,3,2,0,1,4}

Output

5 8 3 2 0
raja
Published on 07-Oct-2021 08:21:08
Advertisements