ed22
ed22

Reputation: 1237

How do I use C++ STL list without iterator?

I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?

Upvotes: 0

Views: 3150

Answers (5)

Pengfei Feng
Pengfei Feng

Reputation: 1

may be you can use another method to do something ,then make it looks like next and prev.

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308216

std::list does not support next or prev by itself. The iterator is used to go from element to element, and you cannot traverse a standard list without it.

Upvotes: 7

Xupicor
Xupicor

Reputation: 71

You could go ahead and use Nemanja Trifunovic idea. By using two lists you could "traverse" the list by popping an element from the front of the "original" list and pushing it at the end of the second "helper" list - having something like this:

[] [1, 2, 3, 4, 5]
    ^
[1] [2, 3, 4, 5]
     ^
[1, 2] [3, 4, 5]
        ^
[1, 2, 3] [4, 5]
           ^
[1, 2, 3, 4] [5]
              ^

And your supposed "clever" avoidance of iterators would work like a bidirectional iterator, pretty much. ^ shows the "current" element. Of course you'd probably make it into a class or whatnot...

The question is - is it really worth it? Just using an iterator would be much simpler (not to mention it's already implemented).

Upvotes: 1

Mark B
Mark B

Reputation: 96261

For a std::list your choices are iteration and standard algorithms. There isn't a way to go forward/back from the item itself.

If you really want an intrusive list, boost does provide that. See http://www.boost.org/doc/libs/1_40_0/doc/html/intrusive/usage.html

Upvotes: 0

Nemanja Trifunovic
Nemanja Trifunovic

Reputation: 24561

You can't have next and prev on each item - std::list is not an intrusive container. If you really don't want to use iterators (why?), you can get to each item by calling front() and then removing it by pop_front() until there are no more items in the list.

Upvotes: 3

Related Questions