Summary of iterator failure in C++--STL

When we use some containers provided by the bottom of the STL, when we insert or erase a container, the iterator is most likely to fail.

What is iterator invalidation

When operating on the container, due to some operations, the location where the element is saved changes, so that an error occurs when operating the iterator pointing to the original location.
E.g

  • ++ operation: After the iterator fails, we have no way to traverse the data in the container through the ++ operation.
  • The data cannot be accessed directly through the iterator.

STL iterator failure scenarios

vector container
  • Since the bottom layer of the vector is a continuous space, when we insert (push_back) it, it is prone to expansion, which will cause the iterator to fail.
  • Delete operation (erase, pop_back), the iterator pointing to the delete operation node will be invalid.

Solution:
Re-acquire the iterator at the location where the iterator fails.

//arr为一个vector对象,删除元素num
for(auto &it:arr)
{
    
    
	if(it == num)
	{
    
    	
		it = arr.erase(it);
	}
}
list

Since the bottom layer of the list is a doubly linked list of leading nodes, there will be no expansion, so the main scenario of the list iterator failure is the delete (earse) operation.

Solution

Reacquire a new iterator.

it = li.erase(it);

Guess you like

Origin blog.csdn.net/qq_42708024/article/details/106135107