Remove Element from C++ Vector: erase() Method

To remove a certain element from a vector, you can use the erase() function together with an iterator. Here is an example:

#include <iostream>
#include <vector>

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

    // 要删除的元素的位置
    int index_to_remove = 2;

    // 获取要删除的元素的迭代器
    std::vector<int>::iterator it = vec.begin() + index_to_remove;

    // 使用erase()函数删除该元素
    vec.erase(it);

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

    return 0;
}

In the above example, we first obtain the position of the element to be deleted, then find the element using an iterator and use the erase() function to delete it. Finally, we output the vector after deleting the element.

bannerAds