[Effective-cpp] Item 1: Uses and Abuses of vector
Gregory Haley
ghaley at venaca.com
Wed Oct 27 10:52:56 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
Did you mean end = vint.end() here?
> (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. Other languages (I think Fortran is one of them)
> solve this problem by having the language specification say
> that the compiler calculates the step and end values just
> once at the start of the loop and uses a saved copy of the
> values in each iteration.
> Programmers need to be aware that these loop-control
> parameters never change even if the variables used do change.
> But that's not a problem as it's just part of the language.
> Not sure what C-family programmers would think of this idea.
I must confess, I took Herb at his word on this when I brought it up for
summary, but the discussion caused me to examine the question more.
It made me curious about what the performance might be, so I wrote a couple
of little programs to build up a really long vector of a million ints, then
loop through it and print out the values (dumping the output to /dev/null)
and timed it. There was no appreciable difference between the two variants
-- indeed what I had thought would be the more efficient loop was slightly
slower. The platform was linux, the compiler g++ 3.2.3. So my guess would
be that this compiler does not recalculate the value of the end iterator
each time.
On your observation about the scope, setting a vint.end() to have a larger
scope than just within the loop, I can foresee dangerous curves ahead, if
someone altered the vector after setting a global end, and then the range
would no longer be correct. The programmer would have to be very careful to
reset it each time.
On another point raised, I would use this sort of loop for a vector that I
intend to modify, especially if the modification involved removing items. I
learned this the difficult way, once trying to iterate through a vector to
remove elements, and at times, the removal would blow the "end iterator"
away.
ciao!
greg.
Gregory Haley
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.779 / Virus Database: 526 - Release Date: 10/19/2004
More information about the Effective-cpp
mailing list