Creating an iterator

Mar 12, 2012 at 10:43pm
So I have a template based class which I call MyStack<T>. I want to create an iterator so that I can iterate through my stack by doing something like this:

for (StackIterator i = myStack.begin(); i != myStack.end(); i++)

The problem I've encountered is thinking of how I would create my begin() and end() functions. My stack is array based so as I push things onto the stack, they get placed starting at 0 and counting upwards so that the "beginning" of my stack is actually the last filled element in my array. How could I create such a function?

Maybe more importantly, what would my StackIterator constructor have to look like? Right now I have the constructor for StackIterator taking in a pointer to the first element in the array and an int representing an index (for where to start the counting). Something like this:

1
2
3
4
5
6
template <typename T>			
StackIterator<T>::StackIterator(const T firstElement,int curIndex)                     
{
	container = firstElement;
	cur = curIndex;
}  //end constructor 


Where container is a pointer to the associated type and cur is an index.
Mar 12, 2012 at 11:11pm
You can either let the iterator contain a pointer to the stack and an index, or it could just contain a pointer to the current element in the stack.

If you just use a pointer begin() will return the iterator that contains a pointer pointing to the last element in the stack. end() returns the iterator with a pointer pointing to the one before the first element in the array. operator++, decrements the pointer by one. operator-- increments the pointer by one.
Topic archived. No new replies allowed.