That really makes more sense now that I look at it. So with the range based for loops, there is no way to actually tell which position you're at? Like, you can't compare the iterator, just the values?
A few other things that I was working on the last few days were rend, rbegin, remove, unique, and erase. Remove and unique are quite easy, or at least I think so. But they both rely on erase which I can't seem to get down.
To start with, I started working on rend and rbegin, thinking they'd just be the opposite of their forward counterparts. Then I looked at how the STL library did it. It uses a reverse iterator. Do I need to create a whole new class for the reverse iterator, or can I just inherit from my iterator class and change what I need? Mine works, aside from the fact that you need to decrement the iterator as opposed to incrementing it like the STL library does it.
Back to the erase function though, here was my first attempt at it that failed miserably.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template<class T>
typename vp::list<T>::iterator vp::list<T>::erase(iterator it) {
if (it == iterator())
return it;
node* prev = it.current->prev;
node* next = it.current->next;
delete it.current;
prev->next = next;
next->prev = prev;
it.current = prev;
mSize --;
return iterator(prev);
}
|
I didn't think about it prior, but why can't my list access the iterator's private members? The list is still the parent class, or would I need to change it to protected to have it work like that? A second attempt at this is going to be me looping through the list with a temp node* and check to see
if (iterator(temp) == it)
I don't see that that's very efficient since it creates a new iterator at each step of the loop and the overhead would be huge.
Also, with the erase functions, the STL doesn't use a reference to the iterators. Won't this cause issues since the node that the iterator points to would be deleted? Or is this not an issue since an iterator would still be modified since it's essentially a pointer? Also, it's supposed to return an iterator. I'm assuming to point at the position before "it" or iterator() if empty.
And finally to unique. Once I figure out how to erase properly, I can just call that when the value passed to unique is equal to whatever dereferenced iterator I'm currently at.
Here's what I have so far for remove:
1 2 3 4 5
|
void vp::list<T>::remove(const T& value) {
for (iterator it(firstNode); it != end(); it ++)
if (*it == value)
it = erase(it);
}
|
Obviously it doesn't work yet since erase isn't working properly, but the line
it = erase(it);
doesn't "feel" right. In my mind it should just be
erase(it);
I know this is a lot at once, but I've been without internet for the last few days so I've been trying to get a bunch of stuff together before posting again.
Again, thanks for all of the help so far. You have no idea how much I've learned from you and how happy it's making me to finally understand how everything works.