0

Assuming the linked list is defined this way:

template <typename Object>
struct Node{
    Object data;
    Node *prev;
    Node *next;

    Node(const Object & d = Object(), Node *p = NULL, Node *n = NULL)
    : data(d), prev(p),next(n){}
};

template <typename Object>
class List
{
public:
   iterator begin(){return iterator(head->next);}
   iterator end(){return iterator(tail);}
....
private:
   Node *head=nullptr;
   Node *tail=nullptr;
...

The iterators:

class iterator
{
public:
    iterator():current(NULL){}
    Object & operator*(){return retrieve();}
    iterator & operator++()
    {
        current = current->next;
        return *this;
    }
    ....
private:
    Node *current;
    ...

There is a problem in this code.

for(iterator<Object> itr = list.begin(); itr != list.end(); itr++ )
    std::cout<<(*itr)->name;

This loop counts until the one item member before the last one. So, the last member of this list is not counted in this loop. How to fix it?

zahmati
  • 1,261
  • 1
  • 10
  • 18
  • `template ` before `struct Node`? or what is `Object`? – 0x6773 Jun 01 '15 at 16:08
  • @mnciitbhu I avoided putting the whole code. I just put the necessary code. The problem is from list and iterator. Object can be any class. it does not matter. – zahmati Jun 01 '15 at 16:12
  • `iterator begin(){return iterator(head->next);` looks wrong (Are head and tail holding valid data? Are these sentinel nodes?) –  Jun 01 '15 at 16:13
  • What is exactly for you the last member ? The nullptr or the one before it ? – perencia Jun 01 '15 at 16:16
  • @perencia `tail` is pointing to the actual last member. I dont use sentinel nodes and `tail->next` is nullptr. – zahmati Jun 01 '15 at 16:19
  • @zahmati `I just put the necessary code` And we still have questions. Better you had posted more than what you thought was necessary. – PaulMcKenzie Jun 01 '15 at 16:20
  • @PaulMcKenzie the linked list has problem. no matter what you put in it. – zahmati Jun 01 '15 at 16:21
  • 1
    @zahmati `tail is pointing to the actual last member.` So of course you won't get to the last entry, because that is what you coded. The `end` iterator is the tail, and your loop says "keep going until you get to the tail". Maybe rethink your design a bit? – PaulMcKenzie Jun 01 '15 at 16:23
  • In fact, as the code is, you could use as the for condition it != somerandomvalue. Maybe you could implement the != operator on the iterator and check for the nullptr on data – perencia Jun 01 '15 at 16:28

1 Answers1

5

Your "end" iterator is a pointer to the last element. That's wrong.

It's supposed to be "one past" the last element.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055