Moved end iterator assignment out of for loops. This reduces the number of
times the end iterator is assigned.