remove value from vector c++

To remove a value from a vector in C++, you can use the erase function along with the remove and end iterators. Here are the steps involved:

  1. Identify the value you want to remove from the vector.
  2. Use the std::remove algorithm to move the elements with the specified value to the end of the vector.
  3. Use the erase function to remove the elements with the specified value from the vector.

Here is a code example that demonstrates how to remove a value from a vector in C++:

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

int main() {
    // Step 1: Identify the value to remove
    int valueToRemove = 42;

    // Step 2: Use the std::remove algorithm
    std::vector<int> myVector = { 1, 2, 42, 3, 4, 42, 5 };
    auto newEnd = std::remove(myVector.begin(), myVector.end(), valueToRemove);

    // Step 3: Use the erase function
    myVector.erase(newEnd, myVector.end());

    // Display the vector after removing the value
    for (int num : myVector) {
        std::cout << num << " ";
    }

    return 0;
}

In this example, the value 42 is removed from the vector myVector. The std::remove algorithm moves all elements with the value 42 to the end of the vector, and then the erase function removes those elements from the vector. Finally, the modified vector is displayed, which would output: 1 2 3 4 5.

Let me know if you have any further questions.