How to search for a specific element in a vector and remove it?

In C++, you can utilize the erase function of std::vector to remove a specific element.

Here is an example using the erase function to delete a certain element:

#include <iostream>
#include <vector>

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

    int elementToDelete = 3;

    // 查找元素
    auto it = std::find(myVector.begin(), myVector.end(), elementToDelete);

    // 删除元素
    if (it != myVector.end()) {
        myVector.erase(it);
        std::cout << "Element deleted successfully." << std::endl;
    } else {
        std::cout << "Element not found." << std::endl;
    }

    // 打印剩余元素
    for (int element : myVector) {
        std::cout << element << " ";
    }
    std::cout << std::endl;

    return 0;
}

In the above example, we first use the std::find function to search for the iterator of the specified element. If the element exists, we use the erase function to delete it. Finally, we iterate through the remaining elements and print them out.

Please note that when using the erase function to delete elements, the subsequent elements will shift forward to fill the gap. Therefore, the original iterators will become invalid after deleting elements. If you want to continue using iterators, you can avoid errors by using the iterator returned by the erase function as the next iterator.

bannerAds