Reputation: 1151
I’m implementing a vector data structure using an array. Naturally the vector class has private variables for the data array, its capacity and size.
I want an iterator as an inner class. The iterator is implemented as a simple int. The ++ operator has to check if it has reached the end of the array. How does it do this? If the Data structure was a linked list, this would be a simple matter of checking if the pointer to the next node== NULL.
I thought of two solutions, a sentinel objet in the list or a pointer to size of the array as a private variable of the iterator inner class. Neither solution seems satisfactory. My question is how is this usually done?
class Vector
{
public
...
private:
int size;
int capacity;
<T> array[];
class iterator
{
public
bool isLast()
private:
int position
}
}
Upvotes: 0
Views: 107
Reputation: 103693
My question is how is this usually done?
How it's usually done is a completely different approach to what you are doing.
In the C++ standard vector class, this is usually done with a simple pointer. You check if it's at the end by comparing it to the vector's end iterator, which also contains (or is) a pointer. The iterator is not able to check its position without another iterator to compare itself against.
if (it == v.end())
If the iterator is not simply a typedef for a pointer, the iterator's overloaded comparison operator will simply forward the operation to the underlying pointer, unless it contains some kind of code for debugging purposes. Comparing iterators from different vectors results in undefined behavior.
If you want an iterator that can verify its own position without the help of another iterator, then your question should not be how it is usually done, because how it is usually done does not allow for that feature. An option would be to store a pointer to the owning vector, along with the integer position. Then you could check if it's at the end with:
if (position == vector_ptr->size())
Upvotes: 3
Reputation: 23793
The iterator constructor would take the vector size as its parameter, and check its current position against it.
Your code sample is not valid C++. If this is not an exercise, consider using std::vector
Upvotes: 1