c++

Delete a element in a vector in c++

1) you can erase a element at a particular position syntax : v.erase(v.begin() + k) where k is the position of element from the start of vector 2)you can delete a particular range of values. syntax : v.erase(v.begin() + i,v.begin() + j)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5); // inserted 1,2,3,4,5 in a vector

    // now i can erase elements using erase function
    // it can be done in two ways.
    //  1) you can erase a element at a particular position 
    // syntax : v.erase(v.begin() + k)  where k is the position of element from the start of vector

    //  2)you can delete a particular range of values
    // syntax : v.erase(v.begin() + i,v.begin() + j)  where i,j is the position of element from the start of vector
    cout<<"elements in the vector after starting to delete elements at index 0: 
";
    for (int i = 0; i < 5; i++)
    {
        cout<<v[0]<<" ";    // erasing elements at index 0
        v.erase(v.begin());
    }


    return 0;
}
Was this helpful?