[Effective-cpp] Item 1: Uses and Abuses of vector

Ric Parkin ric.parkin at ntlworld.com
Wed Oct 27 11:37:32 EDT 2004


On Wed, 27 Oct 2004 17:04:16 +0300, White Wolf <wolof at freemail.hu> wrote:

> Pal wrote:
>>> ...then I guess the call to vint.end() may just be significant. But I
>>> don't really like the usual solutions:
>>>
>>> Solution 1, const iterator outside the loop:
>>> const vector<int>::const_iterator end = vint.begin(); for
>>> (vector<int>::const_iterator it = vint.begin(); it != end; ++it)
>>>
>>> Solution 2, non-const iterator inside the loop:
>>> for (vector<int>::const_iterator it = vint.begin(), end =
>>> vint.end(); it != end; ++it)
> [SNIP]
>> To mention another thing in the formula I dislike, is the redundant
>> vector<int>.
>>
>> for (vint.const_iterator it = vint.begin() ...) or for
>> (vint::const_iterator it = vint.begin() ...)
>>
>> Would remove that.
>
> I still did not see any proof that end() is calculated or that it is
> actually cheaper to take end() out first.  But I have seen broken code 
> too
> many times, where end() was pre-evaluated and the vector (later) changed
> inside the loop.  I find it a bit frustrating that noone has addressed my
> question so far.  Since AFAIK end() is not necessarily calculated, as 
> well
> as even if it is it is inline, I only see a disaster waiting to happen 
> due
> to premature optimisation, and no benefit whatsoever.

Strange, I've never had any bugs like that. Possibly because modifying a 
container while iterating over it is fraught withe danger that I've always 
been very careful with it, or just don't do it.

Ric






More information about the Effective-cpp mailing list