Use the approach with applying the standard algorithm std::remove_if. For example
#include <vector>
#include <iterator>
#include <algorithm>
//...
std::vector<int> myvector{ 3, 3, 3, 3, 3, 3, 3, 1, 2, 3, 4, 5 , 2, 3, 4, 9 };
myvector.erase( std::remove_if( std::begin( myvector ), std::end( myvector ),
[]( const auto &item )
{
return 2 < item && item < 5;
} ), std::end( myvector ) );
for (const auto &item : myvector) std::cout << item << ' ';
std::cout << '\n';
The output of this code snippet is
1 2 5 2 9
Using this for loop
for(int i = 0; i < myvector.size(); i++)
is incorrect. For example if you have a vector with 2 elements and in the first iteration the element with the index 0 was deleted when i will be incremented and equal to 1. So as now i equal to 1 is not less then the value returned by size()
then the second element will not be deleted.
Apart from this such an approach with sequential erasing elements in a vector also is inefficient.