Is there a C++ expert around?? How do I write an iterator for my linked list class in C++??
so i want to write an iterator by writing a function/method like this typedef Node<Type>* iterator void operator++(Node<Type>* rhs){ rhs = rhs->next; }; but where would i put this?? and how would i template it?? would it be a member of the class, friend function, or do i have to make node a class??? also how would i do post increment?? i know post increment works like operator++(int)...but doesn't that have to be a class in order to call list<int.> z; list<int>::iterator x = z.begin(); ++x; here is my code.... thanks! template <typename Type> struct Node{ Node* next; Node* previous; Type data; }; template <typename Type> class list{ public: //constructor list(); //destructor ~list(); void push_back(Type); void push_front(Type); Type& get_front(); Type& get_back(); int size(); private: // pointer to the front of the list Node<Type>* front; //pointer to the back of the list Node<Type>* back; }; template class list<int>; template class list<double>;
Public Comments
- The iterator itself is a templated class. template <class Type> class Iterator { ... } The methods defined for the iterator are used to traverse any type that conforms to specific rules you define in the iterator. This can be linked nodes, a contigous array, or any other referencing method. A good way to implement this is to create an abstract inherited class (e.g. Iterable), that contains the methods or attributes that the inheriting storage class must implement to provide iteration capabilities. The iterator class itself will utilize the methods or attributes defined in the Iterable base class, ensuring that all instances of your iterator type will work with any storage type which implements the Iterable class definition. e.g. template <class Type> class Iterator { // Define iterator methods (e.g. operator++) which may // use methods defined in 'class Iterable' }; template <class Type> class Iterable { public: ... // Resets iterator to begining of list Type* begin(Iterator<Type>& itr) = 0; // Resets iterator to end of list Type* end(Iterator<Type>& itr) = 0; // Returns the pointer to the first element in storage // Used to determine iterator position through comparison Type* begin() = 0; // Returns the pointer to the last element in storage // Used to determine iterator position through comparison Type* end() = 0; }; template <class Type> class List : public Iterable<Type> { ... };
- u answered one off my c++ questions. i understand what you said some what. can you show me how i would apply that to this: http://answers.yahoo.com/question/index;_ylt=ApKzkF9iaQGM0gy6cqErMsTsy6IX;_ylv=3?qid=20071207081212AAPKEPl you can contact me through email if u like.
Powered by Yahoo! Answers