How to use iterators to delete a specific element in a vector?

You can remove a specified element from a vector using an iterator. The specific steps are as follows:

  1. Define an iterator variable pointing to the first element of the vector.
  2. Iterate through a vector using a while loop, checking if the iterator points to the end of the vector.
  3. In the loop, check if the element pointed by the current iterator is the one to be deleted.
  4. If the element is to be deleted, use the erase function to remove the current element and move the iterator to the next element.
  5. If the element is not the one to be deleted, then move the iterator to the next element.
  6. After the end of the loop, the specified element in the vector will be removed.

Here is an example code:

#include <iostream>
#include <vector>

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

    int target = 3;
    auto iter = vec.begin();

    while (iter != vec.end()) {
        if (*iter == target) {
            iter = vec.erase(iter);
        } else {
            ++iter;
        }
    }

    for (auto num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

Running the above code will result in output:

1 2 4 5

In the example above, I used an iterator to traverse the elements in a vector. In each iteration, I first check if the current element is the one to be deleted. If it is, I use the erase function to remove the current element and move the iterator to the next element. If it is not, I simply move the iterator to the next element. Finally, I use a for loop to output the vector after deleting the elements.

bannerAds