remove at index vector c++

To remove an element at a specific index in a vector in C++, you can use the erase() function. Here are the steps to remove an element at a particular index in a vector:

  1. First, include the necessary header file for using the vector container:
#include <vector>
  1. Declare and initialize a vector with some elements:
std::vector<int> myVector = {10, 20, 30, 40, 50};
  1. Determine the index of the element you want to remove. Let's say we want to remove the element at index 2.

  2. Use the erase() function to remove the element at the specified index:

myVector.erase(myVector.begin() + 2);

The erase() function takes an iterator as its parameter, which points to the element to be removed. In this case, we use myVector.begin() + 2 to get the iterator pointing to the element at index 2.

  1. After the erase() function is called, the element at the specified index will be removed from the vector. The size of the vector will be reduced by 1.

Here is the complete code snippet:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> myVector = {10, 20, 30, 40, 50};

    // Remove element at index 2
    myVector.erase(myVector.begin() + 2);

    // Print the updated vector
    for (int element : myVector) {
        std::cout << element << " ";
    }

    return 0;
}

This code will output:

10 20 40 50

The element at index 2 (30) has been successfully removed from the vector.