In an algorithm I'm currently implementing, I need to manipulate a std::list of struct T. T holds a reference to another instance of T, but this reference can also be "unassigned". At first, I wanted to use a pointer to hold this reference, but using an iterator instead makes it easier to remove from the list.
My question is : how to represent the equivalent to null pointer with my iterator?
I read general solution is to use myList.end(), but in my case, I need to test whether the iterator is "null" or not, and I may add or remove elements to the list between the moment when I store the iterator and the moment I remove it from list... Should I make the iterator point to a known list containing the "null" element? Or is there a more elegant solution?
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location using them.
Conventional pointers can sometimes be null, meaning they point at nothing. Iterators, as well, can fail to denote any specific value. Just as it is a logical error to dereference a null pointer, it is an error to dereference an iterator that is not denoting a value.
Overall: Java API has no mean to say if the iterator value may be null or not, unless by stating it explicitly in the documentation. In this case, nothing is stated, however good sense allows to think that a null iterator value will never be returned from Java API methods.
The default value (for iterators that do not define this function) is HasLength() . This means that most iterators are assumed to implement length .
There are no "null" iterators in C++. The value usually used to indicate e.g. "not found" is to return end() . Add another iterator to hold the value of either men. end() or women.
According to this (emphasis by me):
Compared to the other base sequence containers (vector and deque), lists are the most efficient container doing insertions at some position other than the beginning or the end of the sequence, and, unlike in these, all of the previously obtained iterators and references remain valid after the insertion and refer to the same elements they were referring before.
The same applies to erasure (with the obvious exception of iterators referring to a deleted element becoming invalidated). So yes, obtaining end()
will always point to the same "invalid" element and should be safe to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With