I'm writing a code that divides a vector in to equal parts using simple arithmetic on the iterators. My logic might not be very good (although I'm fairly certain this is correct) which might mean I create an invalid iterator past end():
//selectWords is a vector<string>
//No is an unsigned integer.
unsigned wordNo = selectWords.size()/No;
unsigned remainder = selectWords.size()%No;
for(auto i = 0; i < No; ++i){
unsigned extra = remainder ? 1 : 0;
auto b = selectedWords.begin()+(i*wordNo);
auto e = selectedWords.begin() + ((i+1)*wordNo) + extra;
if(e > selectedWords.end()) throw logic_error("Iterator e in GridList::createGrids goes past the end of selectWords.") //shouldn't happen unless I've made a mistake.
...
//do stuff
...
if(remainder > 0) --remainder;
}
The part I'm curious about is e > selectedWords.end()
. If e
is already past end()
, then it is an invalid iterator and I'm not sure whether there is any guarantee that the comparison operator provides defined behaviour. Indeed looking at Ben Voigt's post in this thread and 24.2.7 of N3337 it is clear that using iterator arithmetic to create a past-the-end() iterator is meaningless or illegal. Yet the ability to check whether an iterator is past end() requires that operations on past-the-end() iterators provide defined behaviour.
If it is not valid to do this comparison, is there any other way? Or do I just have to make absolutely sure my logic before compiling is correct?