简体   繁体   中英

Delete element using iterator, without knowing vector

I have a situation. I have used a templated function for one of my task. To this function, I pass iterator by reference. Now, I have to delete few elements from a vector. How do I do this using only iterators? Pl find the respective 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 already asked questions, but they all have a vector in context. so myVec.erase(*first) is easy..

I am also aware that its not a very good way that I pass iterator by reference. But I am following simple rules: use references when something is expected to be changed or to avoid heavy copy. My scenario is fitting first condition.

So How do I delete?

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

You can't. Deleting an element from a container will invalidate all iterators, so you will have to update first and last after each deletion.

  1. Standard library: You must get the reference to the container, or defer the deletion to a place where you have it. There is no way around it. The container is needed to add or remove elements and there is no way to find the container from iterator.

    Additionally, don't forget, that erasing from a vector invalidates all iterators to that vector.

  2. Other libraries: Boost.Intrusive has some containers that allow you to do anything with just a pointer to the object (which doubles as iterator), but they are linked lists, which are generally less efficient than vectors for most purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM