Remove empty elements from a vector in C++

In this tutorial, we will discuss an easy way using which you can remove empty elements from a vector in C++. So let’s get started.

 

1) Including header file:-

Before starting you need to include two header files – vector and algorithm .let’s do that.

#include <algorithm>
#include <vector>

2) Vector creation:

The next step is to create a vector of integers named as v1. its very simple.

vector<int> v1;

3) Inserting elements:

After that, we will insert multiple-element into the vector using the built-in push_back function.

v1.push_back( 0 );
v1.push_back( 1);
v1.push_back( 0);
v1.push_back( 20);
v1.push_back( 40);
v1.push_back( 0);
v1.push_back( 60);
v1.push_back( 0);
v1.push_back( 50);

4) Removing empty elements:

This step is very crucial. We will use the remove and erase function together to eliminate empty elements from the vector.

remove():- it takes the beginning, end, and val as a parameter and is used to remove all the elements which are equal to value. But there is a twist Does it actually remove desirable elements?? The answer is no. It simply overwrites the deleted value with the undeleted one and creates a copy of it. In simple words it deletes but the size of the vector remains unchanged.

erase():- it is used to remove the range of elements or a single element. Additionally, it is capable of changing the size of the vector.

Here we need to eliminate empty elements that mean the elements whose value is equal to zero.

v1.erase( remove( v1.begin(), v1.end(), 0 ), v1.end() );

5) Printing the vector:- Finally, we will print our vector using for loop.

for(int i=0;i<v1.size();i++)
{
    cout<<v1[i]<<" ";
}

Let’s see the entire code…

Implementation

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {

vector<int> v1;

v1.push_back( 0 );
v1.push_back( 1);
v1.push_back( 0);
v1.push_back( 20);
v1.push_back( 40);
v1.push_back( 0);
v1.push_back( 60);
v1.push_back( 0);
v1.push_back( 50);


v1.erase( remove( v1.begin(), v1.end(), 0 ), v1.end() );

for(int i=0;i<v1.size();i++)
{
    cout<<v1[i]<<" ";
}

    return 0;
}

Here comes the end of this tutorial. Isn’t it easy right?

Leave a Reply

Your email address will not be published.