Search code examples
c++listiteratorstderase

Remove item from std::list with only having access to the iterator


std::list is a double linked list. Doesn't that mean that it should be possible to remove an item from a list by only having access to the iterator?

Maybe my question wasn't clear enough.

#pragma once

#include <list>


typedef std::list<int> IntList ;
typedef IntList::iterator IntIterator;

class IntHiddenList
{
private:
    IntList list;
public:
    IntIterator AddInt(int x)
    {
        list.push_front(x);
        return list.begin();
    }
};

int main()
{
    IntHiddenList a;

    IntIterator it = a.AddInt(5);


    // How would I go about deleting 5 from the list using only "it"?
}

Solution

  • Yes, notionally it's possible. However, the standard library does not allow it (it requires the container and iterator to erase).

    However you're in luck: boost provides the boost::instrusive (http://www.boost.org/doc/libs/1_54_0/doc/html/intrusive/list.html) capability to do exactly what you want.