Using <list>
Dose a list iterator keep an index of what number it is in the list?
About to go look through MSDN, not finding anything with google.
Using <list>
Dose a list iterator keep an index of what number it is in the list?
About to go look through MSDN, not finding anything with google.
lists have no real knowledge of "placement" in a list. IE a particular node only knows who is directly infront of it and directly behind it, it does not know that its the 5th node. The iterator only has the knowledge of the node it points to (and of course it knows what the node knows )
I found the function Distance that takes two iterators and returns the distance between them, so I could use that to find the position in the list, but I decided to just keep track of it outside of the list.
My list is a list of menu choices, and I need to know which one is the current selection, not just from the iterator, but the index from the start too.
>Dose a list iterator keep an index of what number it is in the list?
No, but you can acquire that information fairly easily by subtracting the first iterator in the list from the current one.
[edit]
My mistake. I was thinking of random access iterators rather than bidirectional iterators. For anything but a random access iterator the standard library has a function called distance in <iterator>.
[/edit]
Last edited by Prelude; 06-12-2004 at 10:39 AM.
My best code is written with the delete key.
Follow up question.
How can you loop an iterator around to make a list a circular list, what should be below...
Code:list<object>::iterator selection; void NextObject() { selection++; if(--something--) { selection = objectList.begin(); } }
ggCode:if (selection == objectList.end()) { selection = objectList.begin();
Thats not going to work for the other direction is it?
Code:if (selection == objectList.begin()) { selection = objectList.end();
It can work - you just have to increment/decrement your iterator at the right time depending on direction.
end() can be thought of as "one past the last element", where begin() returns the first element. If the container is empty, then begin() == end().
gg
got it now.
thanks guys.Code:if(selection == objectList->begin()) { selection = objectList->end(); selection--; } else selection--;