I have an stl iterator resulting from a std::find() and wish to test whether it is the last element. One way to write this is as follows:
mine *match = someValue;
vector<mine *> Mine(someContent);
vector<mine *>::iterator itr = std::find(Mine.begin(), Mine.end(), match);
if (itr == --Mine.end()) {
doSomething;
}
But it seems to me that decrementing the end() iterator is asking for trouble, such as if the vector has no elements, then it would be undefined. Even if I know it will never be empty, it still seems ugly. I’m thinking that maybe rbegin() is the way to go, but am not certain as to best way to compare the forward iterator with a reverse iterator.
Do this:
That is all. Never gives you undefined behavior, works on all iterators, good day.
Wrap it up for fun:
Giving:
If you’re allergic to utility functions/nice looking code, do:
But you can’t do it on non-random-access iterators. This one works with bidirectional iterators:
And is safe since
end() > itrby the first check.