Reputation: 2541
Is there a way to check that iterator (passed to function as parameter "last") is equal to end() in case I haven't the container itself?
template<typename ForwardIterator>
void MyFunc(ForwardIterator first, ForwardIterator last) {
...
}
Upvotes: 1
Views: 220
Reputation: 70126
Normally, MyFunc
should consider the range including first
and excluding last
just as the standard algorithms do, too.
Which is done in the standard library for the exact reason (or problem) that you are stating. Typical calls to algorithm functions that take e.g. an entire container look like algoname(foo.begin(), foo.end());
where foo.end()
is an iterator that points to an invalid element after the last valid one.
The algorithm would thus need to somehow know whether it can dereference any given iterator (or, at the very least, the one given in last
).
On the other hand, the problem is entirely avoided by defining that last
is exclusive. So, for example iterating over the elements can be done in terms of for(... it != last)
, and this same code will work for any and every value of last
, both ones that refer to valid objects, and the one returned by end()
. The only thing the implementation needs to make sure is that first <= last
, and nothing can go wrong.
Upvotes: 1
Reputation: 1421
AFAIK - no. If you don't have the container, you can't get the ::end() iterator, thus you can't do the comparison. Why not pass the container as reference?
Check out: Testing whether an iterator points to the last item?
Upvotes: 1