How to remove a particular element from a vector?

To remove a specific element from a vector, you can use the erase() function.

Here is an example code:

#include <iostream>
#include <vector>

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

    // 删除第三个元素(索引为2)
    vec.erase(vec.begin() + 2);

    // 打印剩余元素
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

The output is: 1 2 4 5

In the example above, the erase() function was used to delete the third element in the vector, which is the element at index 2. The remaining elements were then printed using a loop.

bannerAds