1

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.

7
  • You're gonna need to post more code before people can properly help you. Something compilable would be nice. Commented May 3, 2014 at 5:47
  • Maybe related to stackoverflow.com/questions/23440462/… Commented May 3, 2014 at 5:49
  • 1
    Do you really mean top++ and not top+1? Similarly middle++ and not middle+1? Commented May 3, 2014 at 5:52
  • 1
    @theharshest: you mean middle = std::next(top). Commented May 3, 2014 at 5:53
  • The postfix++ operator increments the iterator and returns the original value. Commented May 3, 2014 at 5:54

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

I see what is happening. thank you for breaking that down for me.
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.

Comments

1

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.