vector::erase() function with example in C++ STL

C++ STL vector::erase() function: Here, we are going to learn about the erase() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 16, 2019

C++ vector::erase() function

vector::erase() is a library function of "vector" header, it is used to erase/delete elements from the vector, it either removes one element from a specified iterator position or removes a range of elements.

Note: To use vector, include <vector> header.

Syntax of vector::erase() function

    //remove one element
    vector::erase(iterator position);

    //remove a range of elements
    vector::erase(iterator start_position, iterator end_position);

Parameter(s):

In case of removing one element: position – is an iterator position from where element needs to be removed.

In case of removing a range of elements: start_position, end_position – are the start and end iterator positions from where elements need to be removed.

Return value: iterator – It returns an iterator pointing to the element that followed by the last element erased by the vector::erase() function.

Example:

    Input:
    vector<int> v1{10, 20, 30, 40, 50};
    
    //removing one element
    v1.erase(v1.begin() + 2); //removes 2nd index element

    //removing a range of  elements
    v1.erase(v1.begin() + 1, v1.begin() + 3); //removes 1,2 index elements

    Output:
    //if we print the values
    v1: 10 50

C++ program to demonstrate example of vector::erase() function

//C++ STL program to demonstrate example of
//vector::erase() function

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

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //removing one element
    v1.erase(v1.begin() + 2); //removes 2nd index element

    //printing elements after remove one element
    cout << "After removing one element..." << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //removing a range of  elements
    v1.erase(v1.begin() + 1, v1.begin() + 3); //removes 1,2 index elements

    //printing elements after remove one element
    cout << "After removing a range of elements..." << endl;
    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

v1: 10 20 30 40 50
After removing one element...
v1: 10 20 40 50
After removing a range of elements...
v1: 10 50

Reference: C++ vector::erase()


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.