In the following program, the expression
railroad_car
, provided as a template argument in the expression
iterator<railroad_car> train_iterator (train)
, causes the iterator
class to be instantiated so as to deal with railroad cars. The expression
train
provides the new iterator with access to a particular list of
railroad cars.
#include#include const double pi = 3.14159; // Container, railroad-car, and list definitions go here template class iterator { public: iterator (header & header) { first_link_pointer = header.first_link_pointer; current_link_pointer = first_link_pointer; } iterator_parameter* access ( ) { return current_link_pointer -> element_pointer; } void advance ( ) { current_link_pointer = current_link_pointer -> next_link_pointer; } int endp ( ) { return ! current_link_pointer; } void reset ( ) { current_link_pointer = first_link_pointer; } private: link * current_link_pointer; link * first_link_pointer; }; // Define list header: header train; char input_buffer[100]; enum {eng_code = 'E', box_code = 'B', tnk_code = 'T', cab_code = 'C'}; char extract_car_code (char *input_buffer) {return input_buffer[4];} main ( ) { // Collect train elements as usual // Define and initialize iterator class object: iterator train_iterator (train); // Iterate: train_iterator.reset ( ); for (; !train_iterator.endp ( ) ; train_iterator.advance ( )) // Display number, short name, and capacity and terminate the line: cout << train_iterator.access ( ) -> serial_number << " " << train_iterator.access ( ) -> short_name ( ) << " " << train_iterator.access ( ) -> capacity ( ) << endl; } --- Data --- TPW-E-783 PPU-B-422 NYC-B-988 NYC-T-988 TPW-C-271 --- Result --- TPW-C-271 cab 0 NYC-T-988 tnk 1539.38 NYC-B-988 box 3990 PPU-B-422 box 3990 TPW-E-783 eng 0
Note that you can remove the access
, advance
, endp
,
and reset
member functions from the header
class,
forcing all list traversal to be done with a iterator
object.