M
Martin Vejnar
I should have added that your first statement never needs the sizeThe crux of the matter is when it is ok to _dereference_ an iterator.Phlip said:AnonMail2005 wrote:
v.begin () and v.end (), of course are valid. But you can't
dereference (i.e. access) v.end (). And since v.begin () ==
v.end () for an empty vector, why would you think you could
derefernce v.begin () for an empty vector?
Try this:
assert(0 < v.size() || v.end() == v.begin()); // well defined?
assert(&v[0] == &*v.end()); // not always well defined?
assert(0 < v.size() || &v[v.size()] == v.end()); // always well defined?
So for an empty vector, v.end() == v.begin(), while v[0] is invalid because
v.end() is simply magic - there's no secret contained sequence that it's off
the end of.
Your first statement is just iterator comparison - they aren't
dereferenced - so it is safe.
It is not ok to dereference v.end () so *v.end () is not ok. Even if
you do this &*v.end(), so your second statement is not safe.
v[N] where N is an integer is _dereferencing_. So your third statement
is not safe. And neither is v[0] for an empty vector for same reason
as why it is not safe to dereference v.end ().
check.
And your third statement is never safe even with the size check.
Please, do not top-post.
As I understand it, it is safe to have a _pointer_ to an element one
past the end of an array. Isn't it safe to have a _reference_ to the same?
If it is, then &v[0] should be ok, since vector's subscript operator
returns a reference.
Martin