• Register

Vectors in C++ are very useful variables since they are used as a variable length array. They can adapt the size according to the length or the elements inside the vector. If we remove one element then it’ll reduce the size of the vector by one.

In this article we’ll see how to remove an index element of the vector.

Method

To remove an index element from the vector we can use the vector::erase(). erase() is used to delete the specific elements from the container or a specific range of elements and that will reduce the size of the vector.

Syntax to remove an index element will be like this: 

vec.erase(vec.begin() + 1);

If you want to delete more than one element at once:

vec.erase(vec.begin() + 1, vec.begin() + 3);

Example

// CPP program to illustrate 
// working of erase() function 
  
int main() 
{ 
    vector<int> myvector{ 1, 2, 3, 4, 5 }; 
.
.
.
myvector.erase(myvector.begin() + 1);  //deletes the 2nd element
.
.
.
 myvector.erase(myvector.begin() + 1, myvector.begin() + 3);   //to delete more than on element at once
  
     
    return 0; 
} 

Hope this helps.

100 points
7 2