Hi everybody, I need some help for the creation of a const_iterator. I've made a 'stack' class where I use a dynamic array for the data of the stack and I need a const_iterator in order to see all the elements of the stack form the first (at the end of the array) to the last (first element of the array).
Here's the declaration of the class:
1 2 3 4 5 6 7 8 9
template <typename S, typename T>
class stack {
T *dyn_array;
T *first; ///< pointer to the first element of the stack
int _size;
///methods
In file included from main.cpp:1:0:
stack.h: In instantiation of ‘stack<S, T>::const_iterator& stack<S, T>::const_iterator::operator++() [with S = std::basic_string<char>; T = char]’:
main.cpp:39:55: required from here
stack.h:25:5: error: invalid use of non-static data member ‘stack<std::basic_string<char>, char>::dyn_array’
stack.h:284:4: error: from this location
The line 284 is the 'ptr = *(dyn_array[k]);' in the increment of the pointer.
I really don't know how to solve this problem...
Thank you and sorry if i've made english mistakes :)
The 'const_iterator' class is inside the 'stack' class. Isn't this enough? And how can i solve the problem, do I have to copy the array in the 'const_iterator' class? Thank you again.
The 'const_iterator' class is inside the 'stack' class. Isn't this enough?
No. You need access to the actual object.
And how can i solve the problem, do I have to copy the array in the 'const_iterator' class?
No. ptr is supposed to point to stack. Currently it's rather useless.
It can be done like so:
1 2 3 4 5 6 7 8
template <typename S, typename T>
class stack {
...
const_iterator begin() const
{
return const_iterator(this); // k is set to 0 (or _size?) in this case
}
...
By the way: k = k--; should look like this: k--; or --k;
Check whether k is within the valid range. You should at least have an assert if not.