How to delete a specified index element in a vector?

In C++, the erase() function can be used to remove elements at a specified index in a vector. This function takes an iterator as a parameter, which points to the element to be deleted, removes that element, and returns an iterator pointing to the next element.

Here is an example code for deleting elements in a vector by specifying the index:

#include <iostream>
#include <vector>

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

    int index = 2; // 要删除的元素下标

    if (index >= 0 && index < vec.size()) {
        vec.erase(vec.begin() + index); // 删除指定下标的元素
    } else {
        std::cout << "Invalid index." << std::endl;
    }

    // 输出修改后的 vector 元素
    for (int i : vec) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

In the code above, we first define a vector array called vec, then specify the index of the element to be removed as 2. Next, we use the erase() function to delete the element at the specified index, and then output the modified vector elements by iterating through them. The final result is 1 2 4 5.

bannerAds