Delete Vector Index in C++: Simple Guide

In C++, you can use the erase() function of a vector to delete an element at a specific index. The erase() function takes an iterator as a parameter, pointing to the position of the element to be deleted. You can use the begin() function of the vector to get the iterator for the first element, then use the addition operator with the index to get the iterator for the specified position of the element. Here is an example code:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    int index = 2; // 要删除的下标

    // 获取指定下标的元素的迭代器
    auto it = vec.begin() + index;

    // 删除指定下标的元素
    vec.erase(it);

    // 输出删除后的vector
    for (auto num : vec) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

The output result is: 1 2 4 5.

bannerAds