Vector erase() and clear() in C++

Hello everyone. In today’s tutorial we will be learning about two concepts of vectors in C++ which are vector erase() and clear().

First, let’s see what is a vector. A vector is a sequential container class implementing an array with size that can be changed dynamically. This means that adding or deleting an element of the vector can change its size.

The syntax of a vector is

vector <datatype> vectorname;

Now that we know about vectors a little, we will see what erase() and clear() functions do.

Vector erase() in C++

The function erase() removes or erases one or multiple elements from the vector. To remove one element from the vector we pass as the argument the position of the element we want to erase. To remove multiple elements from the vector we pass as argument the initial and the final position of the range of elements which have to be erased. That is, we pass as argument the position from where we want to start erasing and the final position up to where we want to erase the elements.

The syntax is

vectorname.erase(position);
vectorname.erase(startingposition, finalposition);

Here is an example :

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	int i;
	vector<int> v1;               //defining a vector
	cout << "Enter atleast 6 values of vector : ";
	do {
		cin >> i;
		v1.push_back(i);          //entering values in vector until they are integer values
	} while (i);
	v1.erase(v1.begin()+5);           //deletes the element with '5' index, starting with index zero. hence deletes 6th element. 
	v1.erase(v1.begin() + 2, v1.begin() + 4);  //deletes elements starting from index 2 to index 4 ie. 3rd to 5th element
	cout << "\nThe vector has elements :";
	for (unsigned j = 0; j < v1.size(); j++)
	{
		cout << '\n' << v1[j];     // shows the elements of the vector
	}
	return 0;
}

Output :

Enter atleast 6 values of vector : 1 2 3 4 5 6 7 u
The vector has elements :
1
2
5
7

Vector clear() in C++

The function clear() is used to remove or delete all elements from a vector. Hence making the size of that vector zero. It does not take any parameters.

The syntax is

vectorname.clear();

Here is an example :

#include<iostream>
#include<vector>
using namespace std;
int main()
{
  int i ;
  vector<int> v1;               //defining a vector
  cout << "Enter the values of vector : ";
  do {
    cin >> i;
    v1.push_back(i);            //entering values
  } while (i);
  v1.clear();                   //erasing the entire vector so now it contains no element
  cout << "\nThe vector has elements :";
  for(unsigned j=0;j < v1.size();j++)
  { 
    cout << '\n'<<v1[j];        //showing the elements it has which are zero because of the clear command
  }
  return 0;
}

Output :

Enter the values of vector :
12
13
92
r

The vector has elements :

Hope this was helpful. Enjoy Coding!

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *