PDA

View Full Version : stack



mickey
19th November 2006, 03:00
hi, I'm trying to use an my own iterator on my own stack;
But in main.cpp while loop doesn't work. Could anyone read my code?
thanks

jacek
19th November 2006, 03:15
You have to fix operator !=, begin(), end() and remove().

Some hints:
1. Two iterators are equal when they point to the same node.
2. head points to the beginning of the stack.

mickey
19th November 2006, 03:41
I don't understand fine how the iterators costructor work....
anyway, I don't understand what want you say with your 2nd hint: beginning = top stack? If I understand fine, in this code, head points to the top element (the last inserted). Maybe Are you saying that must be the opposite?

mickey
19th November 2006, 05:13
hi,
I changed a little bit and seems ok. But I'm wondering:
why can I use :


cout << it.getValue() << endl;
and not
cout << (*it).getValue() << endl;

and why that error inside op<< (see stack.h)?
thanks

mickey
19th November 2006, 05:45
and in remove what doesn't work...? the way of delete?
and what way to avoid this?


warning C4800: 'Stack<Type,size>::Node *' : forcing value to bool 'true' or 'false' (performance warning)
with
[
Type=int,
size=20
]

jacek
19th November 2006, 16:06
I don't understand what want you say with your 2nd hint: beginning = top stack? If I understand fine, in this code, head points to the top element (the last inserted). Maybe Are you saying that must be the opposite?
In the first version you had:

iterator end() const {
cout << "end " << iterator(*this) << endl;
return iterator( *this);
}

iterator begin() const {
cout << "begin() " << iterator() << endl;
return iterator( );
}
iterator::iterator() creates an iterator that points nowhere, because current == 0 and iterator::iterator( Stack<Type,size>& ) creates an iterator that points to the top of the stack.

Now, you would like to use those iterators like this:

for( Stack<...>::iterator it = stack.begin(); it != stack.end(); ++it ) {
// ...
}
But the problem is that begin() returns an invalid iterator (because it uses iterator::iterator()), so ++it doesn't work.


why can I use :
cout << it.getValue() << endl;
and not
cout << (*it).getValue() << endl;
Because "it" is an object not a pointer.

mickey
20th November 2006, 10:53
how can I declare iterator to use (*it).other_method and 'it = l->begin()'??

jacek
20th November 2006, 15:15
how can I declare iterator to use (*it).other_method and 'it = l->begin()'??
You have to implement operator* and operator-> and make them return references to the value on the stack.