C++ Erasing from list of pairs

这一生的挚爱 提交于 2019-11-29 18:13:34
Christophe

The range-for iterates through a container by giving you access to the elements in the container, and not an iterator to an element.

So in for( auto &it : l0 ), it isn't an iterator to a pair but a reference to a pair. This is why your code doesn't compile

This being said, as πάνταῥεῖ pointed out when he initially closed this as a duplicate of Keeping a valid vector::iterator after erase(), even if your code would compile it wouldn't work because of the invalidation of the iterator following the erase:

Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity.

Workaround

You shall not use the range-for, but the traditional for, and iterating using the return value of erase() :

for (auto it=l0.begin(); it!=l0.end(); ) 
    it = l0.erase(it);  // to avoid incrementing an invalidated iterator

Live demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!