Open In App

How to Delete Element from Specific Position in Vector?

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, vector provides access to its elements using their index values. In this article, we will learn how to delete an element from specific position in vector in C++.

The recommended method to delete an element from specific position in vector is by using vector erase() method. Let’s take a look at an example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // Remove the 2nd index element 6
    v.erase(v.begin() + 2);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 2 4 5 

Explanation: The vector erase() method deletes the element using the iterator to it. The iterator can be found by adding the index to the vector begin() method.

There are also some other methods in C++ to delete an element from specific position in vector. Some of them are as follows:

Using remove() with Vector erase()

The remove() function shifts all the elements after the given index one place to the left and returns the iterator to the new end of the range which only contains the elements that are to be deleted. We can then remove the extra elements using vector erase().

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

    // remove the element at index 2
    v.erase(remove(v.begin(), v.end(),
                   v[2]), v.end());

    for (int i : v)
        cout << i << " ";
    return 0;
}

Output
1 2 4 5 

Using copy() with Vector resize()

The program removes an element from a specific index in the vector by shifting all elements after that index one position to the left using the copy() function. Then, the vector size is decreased by 1 using vector resize() to remove the last element.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};;

    // Copy elements after index 2 one place to left
    copy(v.begin() + 3, v.end(), v.begin() + 2);
  
    // Resize the vector
    v.resize(v.size() - 1);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 2 4 5 

Manually Using Loop

This is basically the internal implementation of vector erase() method. All elements after the given index are manually shifted one position to the left using a loop. Then, the vector pop_back() function is called to remove the last element to remove it.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};

	// Shifting the element after index 2
    for (int i = 3; i < v.size(); i++)
        v[i - 1] = v[i];

    // Removing the last element
    v.pop_back();

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 2 4 5 

Next Article
Article Tags :
Practice Tags :

Similar Reads