remove element by index from vector c++

Code Example:

#include <iostream>
#include <vector>

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

    int indexToRemove = 2;
    vec.erase(vec.begin() + indexToRemove);

    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

Explanation:

  • Include the necessary libraries: <iostream> for input/output operations and <vector> for using vectors.
  • Declare the main function.
  • Create a vector vec with some initial elements.
  • Define the index of the element to remove as indexToRemove.
  • Use the erase function to remove the element at the specified index from the vector.
  • Iterate through the modified vector using a range-based for loop to print the remaining elements.
  • Return 0 to indicate successful program execution.