English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ vector erase() usage and example

C++ Vector (Container)

Delete the specified element in the iterator

Use the delete() function to delete the third element

Syntax

The syntax of vector (vector) v is:

v.erase(pos);
v.erase(start_iterator, end_iterator);

Parameter

pos:It defines the position of the elements to be deleted from the vector (vector).

(start_iterator,end_iterator):It defines the range of elements to be deleted from the vector (vector).

Return value

It returns no value.

Instance1

Delete elements at a specified position.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<char> v{'C','+, '#'};
	v.erase(v.begin()+1);
	for(int i=0; i<v.size(); i++)
	cout << v[i];
	return 0;
}

Output:

C#

Instance2

Delete elements within a specified range

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<string> fruit{ "Mango", "Apple", "Strawberry", "Kiwi", "Banana" };
    cout << "The name of the fruit is:";
    for (int i = 0; i < fruit.size(); i++{
        cout << fruit[i] << " ";
    }
    cout << '\n';
    fruit.erase(fruit.begin()} + 1, fruit.begin() + 3);
    cout << "Delete the elements between mango and kiwi," << '\n';
    for (int i = 0; i < fruit.size(); i++{
        cout << fruit[i] << " ";
    }
    return 0;
}

Output:

The name of the fruit is: Mango, Apple, Strawberry, Kiwi, Banana
After deleting the mango to the kiwi between the elements:
Mango, Kiwi, Banana

C++ Vector (Container)