Blutkoete
Blutkoete

Reputation: 418

Is vector::end() guaranteed to be larger than the storage address of any object in the vector?

The default iterator loop that you find on the Internet looks like this:

for(vector<int>::iterator it=myVector.begin(); it!=myVector.end(); it++)

Now I want to try some more fancy stuff with iterators. I was thinking about run through e.g. every third element of a vector (it + 3 as the incrementor), but I fear that this behaviour explodes if I use a different compiler or a different data set as it + 3 might not be not equal to vector::end(), but at the same time not point to something valid as well.

So I wanted to know if it is always true that if

it >= myVector.end()

then it is not pointing to an element in my vector? Can I use < instead of != and be safe that I won't run into compiler-implementation-specific problems?

Thank you very much!

Upvotes: 1

Views: 366

Answers (2)

gexicide
gexicide

Reputation: 40088

The only iterators that are defined on a vector are iterators pointing to one of its element and the end iterator. Any iterator "greater than" end is undefined anyway. Thus, although your comparison might work, it does not add any value as the added > only makes a difference when comparing with an undefined iterator. As using an undefined iterator implies undefined behaviour, you never ever want to have such an iterator anyway. In addition, this also answers your question: Comparing with an undefined iterator is of course also undefined and therefore not guaranteed to yield a meaningful result.

If you want to check, whether an element is in this vector or in another, then >= won't help you, too, as comparing these iterators is undefined and will usually boil down to a pointer comparison, so the result depends on which vector has a lower address.

So all in all, using >= here simply makes no sense and should therefore be avoided.

As your comment states, you want to iterate through every n-th element of a vector. There a various ways to do this in a defined manner, e.g.:

(it - vec.begin()) + n < vec.size()

Upvotes: 5

James Kanze
James Kanze

Reputation: 153977

Why >=, instead of ==? The end iterator is guaranteed to compare greater than any valid iterator it is not equal to.

Upvotes: 1

Related Questions