0

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"?
}
bofjas
  • 1,186
  • 7
  • 19
  • Yes. that can be done. – andre Aug 19 '13 at 20:47
  • You might show us some of your code and describe better what you are trying to do, because now the questions seems trivially simple, and you probably don't get the answers you are looking for. – hetepeperfan Aug 19 '13 at 20:51
  • It would be awkward to update the size of the list if this were possible, and the committee considers maintaining easy access to the size of the list to be an important feature. – Benjamin Lindley Aug 19 '13 at 21:01
  • Isn't that a bit crippeling for the list? I have a list of pointers to some objects. When deleting the object it could have removed itself from the list by having only the iterator to itself. – bofjas Aug 19 '13 at 21:05
  • Yes, I'd imagine it's quite crippling. To be honest, I pretty much never have any use for a linked list, so I don't notice it. Here's some more information on it though: http://stackoverflow.com/questions/10134836/complexity-of-stdlistsplice-and-other-list-containers – Benjamin Lindley Aug 19 '13 at 21:14
  • @bofjas: This used to be more viable, but it turns out allowing what you want is _even more_ crippling to the list. Namely, that `IntList.size()` took forever to count all the elements. – Mooing Duck Aug 19 '13 at 21:15
  • Maybe they should have two types of lists then? I don't seem to need size for my project atleast. – bofjas Aug 19 '13 at 21:19
  • @bofjas: Actually, I agree. The std lib needs far more container options. – Mooing Duck Aug 19 '13 at 21:21

2 Answers2

2

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
0

No, you will still need the list in order to delete an element.

In STL, iterator only holds the pointer to the data, and provides operations to move through the container. You can see good table description here.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91