On Tue, 21 Dec 2010 15:12:49 -0800 (PST), Joshua Maurice <> wrote:
> On Dec 21, 3:09Â*pm, Andrea Crotti <andrea.crott...@gmail.com> wrote:
>> The "standard" way to iterate over a container should be:
>>
>> std::vector<int>::iterator iter;
>> for (iter=var.begin(); iter!=var.end(); ++iter) {
>> Â* Â* ... Â* Â*
>>
>> }
I read (I think in in one of Herb Sutter's books) that this entails
calculating var.end() every time round the loop, and that using
a local variable set to var.end() can be more efficient. I wondered
whether compilers would be smart enough to optimise this without
any special user coding.
>>
>> for example, right?
>> But I always end up using
>> for (size_t i=0; i < var.size(); ++i) {
>> Â* Â* ...
>>
>> }
>>
>> (unless I'm using maps)
>>
>> because it's much shorter to write and I don't need the iterator. Â*But
>> are there any real differences using this two different possibilities?
>
> Some compilers might optimize one better than the other. For
> std::vector, I hope that both for loops would produce the same
> assembly output, but I am frequently surprised as the bad quality of
> some commercial compilers.
>
> Also, some containers don't support constant time indexing, so
> iterators is your only real option, such as std::map.
>
> Also, C++0x will solve this typing annoying nicely with auto, and even
> better with foreach loops aka range based for loops.
>> Â* Â* ...
>>
>> }
>>
>> for example, right? But I always end up using for (size_t i=0; i < var.size(); ++i) { Â* Â* ...
>>
>> }
>>
>> (unless I'm using maps)
>>
>> because it's much shorter to write and I don't need the iterator. Â*But are there any real differences using this two different
>> possibilities?
>
> Some compilers might optimize one better than the other. For std::vector, I hope that both for loops would produce the same
> assembly output, but I am frequently surprised as the bad quality of some commercial compilers.
>
> Also, some containers don't support constant time indexing, so iterators is your only real option, such as std::map.
>
> Also, C++0x will solve this typing annoying nicely with auto, and even better with foreach loops aka range based for loops.
It will be great if it allows a foreach that doesn't require the use
of a function or function object outside the loop. While I
think this technique may be useful in some cases, I think it can
be cumbersome. I recently used a foreach for what would otherwise
been a fairly straightforward loop, but found myself creating a function
object and then ensuring that it was constructed with the
right context, which would have otherwise been available in the body
of the loop 'for free'.
Chris Gordon-Smith
www.simsoup.info