Delete an element using an iterator, without knowing the vector

I have a situation. I used a template function for one of my tasks. To this function, I pass an iterator by reference. Now I have to remove some elements from the vector. How to do this using only iterators? Pl find the appropriate code:

template <class BidirectionalIterator, class Iterator> bool SomeFunc( BidirectionalIterator& first, BidirectionalIterator& last, Iterator anotherVecBegin ) { while((first+1) != last) { if(some_condition) // delete (first); HOW? else if(some_other_condition) // delete (first + 1); HOW? } // add something to another vector using anotherVecBegin return true; } 

There are many questions already asked, but they all have a vector in context. therefore myVec.erase(*first) easy ..

I also know that this is not a very good way to pass an iterator by reference. But I follow simple rules: use links when something needs to change or to avoid a heavy copy. My script meets the first condition.

So how to remove?

+5
source share
3 answers

You cannot change the container if all you have are iterators for the elements of the container. The whole point of iterators separates the concept of a container from the concept of a range of elements, so that algorithms can be expressed universally in terms of the latter, without worrying about the former. That's why we have a remove algorithm that permutes the range and returns an iterator suitable for erasing items from the container, but the removal should be done by someone who knows the container.

+6
source

You can not. Removing an item from the container will invalidate all iterators, so after each removal you will have to update first and last .

+2
source
  • Standard library: you should get a reference to the container or delay the removal to the place where you have it. There is no such thing. A container is needed to add or remove items, and there is no way to find a container from an iterator.

    Also, do not forget that deleting from a vector cancels all iterators on this vector.

  • Other libraries: Boost.Intrusive contains several containers that allow you to do anything with just a pointer to an object (which doubles as an iterator), but they are linked by lists, which are usually less efficient than vectors for most purposes.

+2
source

Source: https://habr.com/ru/post/1240324/


All Articles