C++ iterators problem

前端 未结 3 1782
傲寒
傲寒 2021-01-20 15:15

I\'m working with iterators on C++ and I\'m having some trouble here. It says \"Debug Assertion Failed\" on expression (this->_Has_container()) on line interIterator++. Dist

3条回答
  •  离开以前
    2021-01-20 16:01

    You can't remove elements from a sequence container while iterating over it — at least not the way you are doing it — because calling erase invalidates the iterator. You should assign the return value from erase to the iterator and suppress the increment:

    while (interIterator != externIterator->end()){
       if (interIterator->getReference() == tmp){
           interIterator = externIterator->erase(interIterator);             
       } else {
           ++interIterator;
       }
    }
    

    Also, never use post-increment (i++) when pre-increment (++i) will do.

提交回复
热议问题