سؤال

I have a linked list of objects where each object has a linked list of char.

I declared three iterators:

top = someList.begin();

middle = top++;

bottom = middle++;

When I print the list of each of those iterators, it doesn't match up with what the full list looks like.

Basically by the end of those declaration statements top becomes the middle row, middle is what its meant to be and bottom becomes what the top row is meant to be.

I am assuming it's the way I declare the iterators with the increments. Any help is much appreciated.

هل كانت مفيدة؟

المحلول

Let's see what happens after each statement. assume position marks 0,1,2,3... for the list
The problem is in the post ++

top = someList.begin();
//top=0

middle = top++;
//middle=0
//top=1

bottom = middle++;
//bottom=0
//middle=1
//top=1

نصائح أخرى

This is a shot in the dark, based on your description here:

basically by the end of those declaration statements top becomes the middle row, middle is what its meant to be and bottom becomes what the top row is meant to be.

When you assign middle = top++, you are assigning middle to the old value of top, and simultaneously incrementing top. It is the same idea in the second assignment.

Try the following

#include <iterator>

//...
top = someList.begin();

middle = std::next( top );

bottom = std::next( middle );

Or you could write the same without using function std::next

top = someList.begin();

++( middle = top );

++( bottom = middle );

Or more readable

top = someList.begin();

middle = top;
++middle;

bottom = middle;
++bottom;

Or you could use function std::advance

#include <iterator>

//...
top = someList.begin();

middle = someList.begin();
std::advance( middle, 1 );

bottom = someList.begin();
std::advance( bottom, 2 );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top