Skip to main content
gamedev.net
🔒 Locked

Iterators

Started by lord4n 4 replies 600+ views
Original Post
lord4n
lord4n
I am trying to build my own List class (just for learning) and i was stuck in the "Iterator" thing. how can i make my class an iterator ?
True knowledge exists in knowing that you know nothing.
jrmiller84
jrmiller84
When you say list class, do you mean you are trying to simulate the creation of a linked list? IE your own linked lists class?
I will forever be a student.
lord4n
lord4n
yes.
True knowledge exists in knowing that you know nothing.
Kincaid
Kincaid
linked lists are easy

first define a pointer to the class that needs to be linked.

typedef class list_item* item

then you use this in the clas itself to point to the next

so;


class list_item
{
private:
float a_value;
item next_item

public:
friend item& get_next_item (item i){return i->next_item;}

list_item (): next_item(0)
};

make the constructor create a null-pointer to begin with, and from then on you can cycle the list by calling get_next_item(a list_item)
to create a new class in the list call the same

item a = ...// retrieve a list_item_class
get_next_item (a) = new list_item ();

or to get the last item in a list use;

list_item last_item ( list_item i )
{
if(!get_next_item(i))
return i
else return last_item ( get_next_item(i))
}

hope this is what you ment ... :)
jrmiller84
jrmiller84
I agree with Kincaid, that's how I learned to do linked lists (if that's what you mean) until I found out that they are already built for you. It is definately a good exercise though to learn how they work. I would quickly switch after you're comfortable with them ;) hah
I will forever be a student.
Oluseyi
Oluseyi
Quote:
Original post by lord4n
I am trying to build my own List class (just for learning)
and i was stuck in the "Iterator" thing.
how can i make my class an iterator ?

The iterator is a separate, nested class that provides access and traversal functionality via a uniform interface. It's very useful for (template-based) generic programming because algorithms can be written without any knowledge of internal data structure or implementation by using these iterators.

class List{private:  ... your class implementation here ...public:  ... your class interface here ...  class Iterator  {    private:      ... iterator implementation details here ...    public:      Iterator& operator ++ ();      Iterator& operator -- ();      Node_Type& operator * ();      Ret_Type operator -> ();      ... rest of iterator interface here ...  };};

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.