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.
- We include the necessary headers for input/output, vectors, and algorithms.
- Inside the
main
function, we define the vectorvec
and the valuevalue_to_remove
which we want to erase from the vector. - We use the
erase
andremove
algorithms from the<algorithm>
header to remove the specific element from the vector. Theremove
algorithm moves all elements that are equal tovalue_to_remove
to the end of the vector, and then theerase
method removes these elements from the vector. - We then loop through the modified vector and print its elements to verify that the specific element has been removed.