Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
Adorn Avatar asked Jan 11 '16 09:01

Adorn


People also ask

How do I remove a specific element from a vector position?

vector::erase() erase() function is used to remove elements from a container from the specified position or range.

Does iterator delete invalidate?

Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated.


1 Answers

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.

like image 168
Kerrek SB Avatar answered Sep 19 '22 22:09

Kerrek SB