I want to erase all elements with value greater 2 and less 5 here is the code :
vector<int> myvector{3, 3, 3, 3, 3, 3, 3, 1, 2, 3, 4, 5 , 2, 3, 4, 9};
vector<int>::iterator it;
it = myvector.begin();
for(int i = 0; i < myvector.size(); i++)
{
if(myvector[i] > 2 && myvector[i] < 5)
{
myvector.erase(it+i);
}
}
for(int i = 0; i < myvector.size(); i++)
{
cout << ' ' << myvector[i];
}
output: 3 3 3 1 2 4 5 2 4 9
Where is the problem.
The problem is with using the
erasefunction in a loop with iterators of that modifiedvector. From the cppreference page for theerasefunction (bolding mine):Correctly erasing elements inside a loop can be done, but it is a little tricky. The easier way is to apply the erase-remove-idiom. Or if you can use C++20, have a look at
std::erase_if.