Re: Strings with Templates not working?
On Jun 20, 10:27 pm, Markus Pitha <newsgroupsNOS...@pithax.net> wrote:
[...]
I have an old C book. They write the following in this book:
free(head);
head = head->next;
I thought this can not work, because how can I free the "head" of the
list _at first_ without losing the whole list?
It's undefined behavior. It happened to work with some early
implementations. (In practice, it will work with a lot of
current implementations, at least in a single threaded
environment.) By chance. Don't do it.
The obvious correct way to do this is:
TKnoten* tmp = head->next ;
free( head ) ;
head = tmp ;
template <class T>
T ListT<T>::get(int i) {
TKnoten *iterator = new TKnoten();
HUH? Why are you creating another 'TKnoten' here?
How can I iterate over the whole list then without an extra object?
Why do you need an extra object to iterate over the whole list?
My pre-standard DLList didn't have one. Type-checking is a bit
easier to manage if you have the extra object, but what I did
was define a basic node class, without any data, but with the
pointers, and then derive from that with the data. Something
like:
struct Node
{
Node* next ;
Node* prec ;
} ;
template< typename T >
struct ConcreteNode : public Node
{
T value ;
} ;
The DLList class contained a Node which served as root, so to
iterate, you'd do something like:
for ( Node* current = root.next ;
current != &root ;
current = current->next ) {
ConcreteNode< T >* p
= static_cast< ConcreteNode< T >* >( current ) ;
// ...
}
Alternatively, you can use special values in the pointers at the
end (NULL works fine), and keep separate head and tail pointers
in the List object, so iteration becomes:
for ( Node* current = first ;
current != NULL ;
current = current->next ) ...
This is perhaps easier to understand than using a circular list
with a dedicated node, but requires special casing for
insertions and deletions at either end.
--
James Kanze (GABI Software, from CAI) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34