Erasing a container item using iterators

In my current homework assignment, I created an iterator class for a list. I am stuck in creating a good function erase(iterator where).

Current code (reduced to question):

class List
{
    class _Iter
    {
        friend class List;
    public:
        _Iter(ListElem *pCurr, List *pList);

        /* *, ->, ++, --, == and != operators overloaded */

    private:
        ListElem *pCurr_; List *pList_;
    };

    typedef _Iter iterator;

    iterator erase(iterator where);
};

when erasing is done like this:

// Precondition: List has been checked for size > 0.
List::iterator List::erase(List::iterator& where)
{
    // Erasing only element in list.
    if(where == end() && where == begin())
    {
        pop_back(); // or pop_front();
        return iterator(0, this);
    }

    // Elem at end
    if(where == end())
    {
        pop_back();
        return end();
    }
    else 
    {
        // Elem at beginning
        if(where == begin())
        {
            pop_front();
            return ++begin();
        }
    }

    // Elem somewhere between beginning and end.
    iterator temp(where);
    // The node next to pCurr_ should point to the one before pCurr_
    where.pCurr_->next->prev = where.pCurr_->prev;
    // The node before pCurr_ should point to the one after pCurr_
    where.pCurr_->prev->next = where.pCurr_->next;
    // Return the node after pCurr_
    ++temp;
    delete where.pCurr_;
    --size_;
    return temp;
} 

The first three cases: only the element, the element at the end and the element at the beginning - everything is in order. Coded fine and requires absolutely no knowledge and personal access to members _Iter. However, if the item is not in these positions, then I (apparently) have no choice but to break encapsulation and directly modify pCurr_ (list item).

? STL, _Next_Node_(/* stuff */) _Prev_Node_(/* stuff */), . Google , , .

: , , pCurr_?

+3
2
  • , , . . , .

  • end() , . ( , l.rbegin(). Base(), ).

  • , .

  • pCurr?

+3

. , . . , . , .

, begin() == end(), , , , . end() " " .

+2

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


All Articles