remove specific element from vector c++

Remove Specific Element from Vector in C++

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

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

    vec.erase(std::remove(vec.begin(), vec.end(), value_to_remove), vec.end());

    for (int i : vec) {
        std::cout << i << " ";
    }

    return 0;
}

In this example, we have a vector of integers vec containing values 1, 2, 3, 4, and 5. We want to remove the specific element with the value 3 from the vector.

  1. We include the necessary headers for input/output, vectors, and algorithms.
  2. Inside the main function, we define the vector vec and the value value_to_remove which we want to erase from the vector.
  3. We use the erase and remove algorithms from the <algorithm> header to remove the specific element from the vector. The remove algorithm moves all elements that are equal to value_to_remove to the end of the vector, and then the erase method removes these elements from the vector.
  4. We then loop through the modified vector and print its elements to verify that the specific element has been removed.