I used two sorts of traversal loops here (more for illustration than anything else). You do not have an indexing notation [i] available to you for lists, so you need some other means of traversing your list.
for ( auto L : ListOfLists )
This is a range-based for loop. It basically says "for each element - let's call it L - of ListOfLists do something". The elements of ListOfLists are of type list<string> so I could write
for ( list<string> L : ListOfLists )
instead. However, since the compiler knows perfectly well what sort of objects are held in ListOfLists you can just use auto and sit back and let the compiler automatically select the right type for you. If you want to be super-efficient you could use a reference for the element instead:
for ( auto &L : ListOfLists )
, and if you are supremely risk averse, then const-qualify it as
for ( const auto &L : ListOfLists )
. On the other hand, you are only talking about writing out one line of text here ...
for ( auto p = L.begin(); p != L.end(); p++ )
This is closer to the standard
for ( i=0; i < imax; i++) |
type of loop, except that, since indexing isn't available to you, you have to use an iterator. The full form would be
for ( list<string>::iterator p = L.begin(); p != L.end(); p++ )
but auto doesn't half save some typing for the lazy now.
You do indeed have to make your own traverser of lists. There are many ways, but you will basically have to start at the HEAD node and keep following the NEXT pointer ... until it points to nullptr (or whatever you are using to signify the end).
I've no idea what your linked list looks like, but when I wrote one my traverse-and-display routine looked like
1 2 3 4 5 6 7 8 9 10
|
template <class T> void MyList<T>::display()
{
Node<T> *n = head;
while( n != nullptr )
{
cout << n->value << " ";
n = n->next;
}
cout << endl;
}
|
Alternatively, you could write your own iterators to traverse the list, but that is beyond my capabilities.