C++ Vector erase() Function Guide

The erase function in C++ vectors is used to remove one or more elements from the vector. It removes the element at a specified position or a specified range of elements from the vector and updates the size of the vector.

There are two ways to use the erase function.

  1. Remove a single element: pass an iterator parameter pointing to the position of the element to be deleted, the function deletes the element, and returns an iterator pointing to the next element after the deleted element.
  2. Remove multiple elements: pass two iterator parameters specifying the range of elements to be deleted, the function removes all elements within that range, and returns an iterator pointing to the element after the deleted ones.

For example, the following code demonstrates the usage of the erase function:

#include <iostream>
#include <vector>

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

    // 删除单个元素
    numbers.erase(numbers.begin() + 2); // 删除索引为2的元素

    // 删除多个元素
    numbers.erase(numbers.begin(), numbers.begin() + 2); // 删除前两个元素

    // 输出向量中的元素
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

The output result is:

4 5

In the example above, the vector begins with elements 1, 2, 3, 4, 5. Initially, the erase function is used to remove the element at index 2, which is the number 3. Then the erase function is used again to delete the elements at index 0 and 1, which are the numbers 1 and 2. Finally, only the numbers 4 and 5 remain in the vector, which are then output.

bannerAds