how to erase a certain value from a vector in C++

To erase a certain value from a vector in C++, you can follow these steps:

  1. Find the position of the element you want to erase using the std::find algorithm. This algorithm searches for a given value in a range and returns an iterator pointing to the first occurrence of the value, or the end iterator if the value is not found.
auto it = std::find(vec.begin(), vec.end(), value);
  1. Check if the iterator returned by std::find is not equal to the end iterator, which indicates that the value was found in the vector.
if (it != vec.end()) {
    // Element found, erase it
}
  1. If the value was found, use the erase function to remove the element from the vector. The erase function takes an iterator pointing to the element to be erased and returns an iterator pointing to the next element in the vector.
vec.erase(it);

After these steps, the value will be removed from the vector.

Here's the complete code snippet:

#include <iostream>
#include <vector>
#include <algorithm>

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

    auto it = std::find(vec.begin(), vec.end(), value);

    if (it != vec.end()) {
        vec.erase(it);
    }

    // Print the modified vector
    for (const auto& element : vec) {
        std::cout << element << " ";
    }

    return 0;
}

This code will remove the value 3 from the vector vec and print the modified vector as 1 2 4 5.