문제

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