新技能Get!
对于c++里面的容器, 我们可以使用iterator进行方便的遍历. 但是当我们通过iterator对vector/map等进行修改时, 我们就要小心了, 因为操作往往会导致iterator失效, 之后的行为都变得不可预知. 比如:
cplusplus的reference里对 std::vector::erase 的描述是:
Iterators, pointers and references pointing to position (or first) and beyond are invalidated, with all iterators, pointers and references to elements before position (or first) are guaranteed to keep referring to the same elements they were referring to before the call.
只有删除元素前面的iterator还保持有效, 之后的遍历行为不可预知.
对于vector, erase会返回下一个iterator, 因此我们可以使用如下的方法:
对于map, 删除iterator只会影响当前的iterator, 因此使用for循环就够了, 比如:
但是更推荐的做法是在erase前让iterator指向下一个元素
http://stackoverflow.com/questions/4645705/vector-erase-iterator
http://stackoverflow.com/questions/4600567/how-can-i-delete-elements-of-a-stdmap-with-an-iterator
Original: https://www.cnblogs.com/dabaopku/p/3912662.html
Author: 大宝pku
Title: c++如何遍历删除map/vector里面的元素
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/535506/
转载文章受原作者版权保护。转载请注明原作者出处!