removing elements witha n interator c++ code example
Example 1: remove value from vector c++
#include <algorithm>
#include <vector>
std::vector<int> vec {2, 4, 6, 8};
int value = 8
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
Example 2: removing element from vector while iterating c++
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6 };
auto it = v.begin();
while (it != v.end())
{
if (*it & 1) {
it = v.erase(it);
}
else {
++it;
}
}
for (int const &i: v) {
std::cout << i << ' ';
}
return 0;
}