Removing elements from STL Conatainers.

While removing a number of items from containers such as list and vectors, we should always remove them in reverse order.

If we start from the beginning, then after removing one element, the positions of the elements in the container will change and then the positions of the items to be removed will not match to the present elements in the container.

Thus always start removing in the reverse order.

e.g.

If there is a list of 10 elements.

You have to remove 4th, 6th and 9th element.

Now if you remove 4th element first, 6th element will now become 5th element. Now if you remove 6th element, it will not be the element you want to remove.

But if you start removing in the reverse order i.e. first remove the 9th element. Now the position of the 4th and 6th elements is not affected and thus can be easily removed.

While removing a number of elements from the list and vector always start deletion in the reverse order.

No comments: