Answer the question
In order to leave comments, you need to log in
How to remove vector element by index?
I'm trying to delete a vector element if the field matches what I entered from the keyboard, the method I found on the Internet deletes only two elements, although it should, in theory, delete everything, the function code:
void Delete(vector <Train *> &train)
{
string dest;
cout << "\nВведите пункт назначения для удаления поезда:" << endl; cin >> dest;
for (int i = 0; i < train.size(); i++)
if (train[i]->GetDest() == dest)
train.erase(train.begin() + i);
}
Answer the question
In order to leave comments, you need to log in
Your code doesn't work because, let's say for i==3 you delete an element. Now the element at index i will be the next element after the deleted one. You will not check it and at the end of the iteration i will increase by 1. Thus, you will simply skip following the element to be removed.
There are many ways to fix this oversight:
1) When deleting, decrement i by 1 so that the next i++ from the for loop is cancelled.
2) Instead of a for loop, use a while where you increment i only if the element is not removed.
3) Instead of an if, use a while loop that removes the element at position i until it needs to be removed (don't forget to check that the element does exist - you could remove the last element and i would be outside the array).
4) (best option) Use remove. Not only do you not have to reinvent the wheel, but this method will also be an order of magnitude faster than deleting one element at a time. Because with each deletion, a part of the array is shifted and you get quadratic running time out of the blue.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question