How can elements be removed while iterating through a vector?

In C++, you can use iterators to traverse and erase elements in a vector. Here is an example code:

#include <iostream>
#include <vector>

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

    // 使用迭代器遍历vector
    for (auto it = numbers.begin(); it != numbers.end(); ) {
        // 判断元素是否需要删除
        if (*it % 2 == 0) {
            // 删除元素,并将迭代器指向下一个元素
            it = numbers.erase(it);
        } else {
            // 迭代器指向下一个元素
            ++it;
        }
    }

    // 输出结果
    for (auto num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

The output result is:

1 3 5

In the code above, we are using an iterator ‘it’ to iterate through the elements in a vector. If the current element is even, we use the erase function to remove that element and move the iterator to the next element. If the current element is odd, we simply move the iterator to the next element without deleting anything. This allows us to iterate through and remove elements from the vector.

bannerAds