深入理解STL list erase

发布于:2024-12-18 ⋅ 阅读:(14) ⋅ 点赞:(0)

1、list erase后,当前的迭代器失效,返回指向下一个节点的迭代器

#include<list>
#include<iostream>
#include<vector>
using namespace std;

int main()
{
	list<int> ls;
	ls.push_back(1);
	ls.push_back(2);
	ls.push_back(3);
	list<int>::iterator it = ls.begin();
	for ( it = ls.begin(); it != ls.end();)
	{
		if (*it == 2)
		{
			ls.erase(it);
		}
		else
		{
			cout << *it << endl;
			it++;
		}
	}

	return 0;
}

ls.erase(it);后,it失效,再对其进行++将会导致软件崩溃,erase后返回一个新的有效的迭代器 it = ls.erase(it);才是正确的

list erase源码如下

    iterator erase(const const_iterator _Where) noexcept /* strengthened */ {
#if _ITERATOR_DEBUG_LEVEL == 2
        _STL_VERIFY(_Where._Getcont() == _STD addressof(_Mypair._Myval2), "list erase iterator outside range");
#endif // _ITERATOR_DEBUG_LEVEL == 2
        const auto _Result = _Where._Ptr->_Next;
        //销毁当前节点
        _Node::_Freenode(_Getal(), _Mypair._Myval2._Unlinknode(_Where._Ptr));
        //返回一个新的迭代器
        return _Make_iter(_Result);
    }
    _Nodeptr _Unlinknode(_Nodeptr _Pnode) noexcept { // unlink node at _Where from the list
        _Orphan_ptr2(_Pnode);
        _Pnode->_Prev->_Next = _Pnode->_Next;
        _Pnode->_Next->_Prev = _Pnode->_Prev;
        --_Mysize;
        return _Pnode;
    }