Abhi Sarkar
Abhi Sarkar

Reputation: 25

The question on iterator begin() function

Below the link where I see how iterator begin function works but not understand clearly.

https://secweb.cs.odu.edu/~zeil/cs361/web/website/Lectures/iterators/pages/implem.html

In their, I see begin function but don't understand how it works

  Book::iterator Book::begin()
  {
   Book::iterator it;
   it->pos = authors;
    return it;
  };

in this it is object but in this it-> what is doing i think this overloaded with operator->() I think it work like a it.operator->().pos but I don't know for sure after that why it return it my question is what is return it does I'm not getting clear picture for this.

Upvotes: 0

Views: 160

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84561

Your class Book contains a struct AuthorListNode and a pointer to type struct AuthorListNode that is used as a pointer to the beginning node in a linked list:

class Book {
  struct AuthorListNode {
     Author data;
     AuthorListNode* next;
  };
  ...
private:
  ...
  AuthorListNode* authors;  // linked list of pointers to authors
  ...
};

In the iterator for Book::iterator Book::begin(), it->pos = authors; sets the pos member of the iterator it to the beginning of your linked-list returning the pointer it with the pos member initialized to point to the start of the linked-list allowing you to iterate from the beginning of authors.

(note: AuthorIterator::pointer AuthorIterator::operator->() has return &(pos->data); so as identified by &AlanBirtles in his answer using it->pos may well be a bug in the documentation)

Upvotes: 1

Alan Birtles
Alan Birtles

Reputation: 36389

I'm pretty sure this is a bug, it should just be it.pos = authors as it is trying to set the value of the iterator not dereference the iterator (which is not initialised so will probably crash) and set a value on the pointed to node.

Upvotes: 1

Related Questions