notes45 - Notes for CS 251 February 5th, 2007 Notes by...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Notes for CS 251 February 5th, 2007 Notes by Jason Faas Template Example is in lab3-src/ from the lab3 handout Writing an Iterator Iterator: It is a class that can be used to iterate over the elements of a data structure Example: Writing an Iterator Class template for the generic class we wrote before. Also in ListGeneric.h template <typename Data> class ListGeneric Iterator { ListEntry<Data> * _currentEntry; ListGeneric<Data>* _list; public: ListGenericIterator(ListGeneric <Data> *list); bool next(Data &data); }; template<typename Data> ListGenericIterator<Data>::ListGenericIterator(ListGeneric<Data>* list) { //constructs a new iterator for the list passed as argument _list=list; _currentEntry=_list->_head; } template <typename Data> bool ListGenericIterator<Data>::next(Data &data) { if(_currentEntry==NULL) { return false;//end of list } //We are in middle of list data=_currentEntry->_data; //point to next entry _currentEntry=_currentEntry->_next return true; ___________________________________ Also in ListGenericTest.cc int main(int argc,char** argv) { . . . //testing iterator for lists const char *(array)={"one","two","three","four","five"}; int n=sizeof(array)/sizeof(const char*) //will give (5*4)/4=5 //create a list of strings ListGeneric<const char*>* listString=new ListGeneric<const char*>; //insert strings int i; for(i=0; i<n; i++) { listString->insert(array[i]); } //using iterator to print elements //in the list ListGenericIterator<const char*> *iterator =new ListGeneric Iterator<const CHAR*>(listString); const char* s; while(iterator->next(s)) { printf("%s\n",s); } //We don't need the iterator anymore //so we can delete it delete iterator; _____ NOTE: So far we have been using "new" to create instances of a template. However, you can have also local variable that are also instances of a template....
View Full Document

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 9

notes45 - Notes for CS 251 February 5th, 2007 Notes by...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online