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

Balog Pal pasa at lib.hu
Wed Oct 27 10:00:15 EDT 2004


> ...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)
>
> I don't like solution 1 because the iterator 'end' has too large a
> scope. I only want it to be accessible up to the end of the loop, not to
> the end of the enclosing block. I don't like solution 2 because the
> iterator is not const. The compiler would let me accidentally change its
> value inside the loop.

I didn't find it a real problem.  The end marker shall never appear in the
body, thus will not be modified by accident.
[I used the first formula for a long time, then switched the the second as
soon as saw it -- and I never thought to switch back since. ]

If I were allowed to introduce a single constifier, I'd rather use it on
'it'. In 99% of my loops the iterator shall not be modified outside the
for() header -- but as it does appear in the loop, it is open to accidental
modification.

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.





More information about the Effective-cpp mailing list