How to delete the nth element from a vector?

To erase the nth element in a vector, the erase() function in C++ can be used. This function requires two parameters: the first parameter is an iterator pointing to the element to be deleted, and the second parameter is an iterator pointing to the next position of the range to be deleted.

Below is an example code demonstrating how to delete the nth element in a vector.

#include <iostream>
#include <vector>

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

    int n = 3; // 要删除的第n个元素

    if (n >= 1 && n <= vec.size()) { // 确保n的值在合法范围内
        vec.erase(vec.begin() + n - 1); // 删除第n个元素
        std::cout << "删除成功!" << std::endl;
    } else {
        std::cout << "删除失败,索引无效!" << std::endl;
    }

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

    return 0;
}

In the example code above, we first define a vector with 5 elements. Then, we specify the element to be removed (in this case, 3) and perform a validity check. If the value of n is within the valid range, we use the erase() function to delete the element at position n. Finally, we output the vector after deletion.

The output result is:

删除成功!
1 2 4 5

It can be seen that the third element (with a value of 3) has been successfully deleted, reducing the number of elements in the vector by one.

bannerAds