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

Gregory Haley ghaley at venaca.com
Tue Oct 26 15:15:31 EDT 2004


> There are some other minor topics which I will list with all 
> the item's guidelines.
> 
> o) Remember the difference between size/resize and capacity/reserve
> 
> o) Be const correct. In particular, use const_iterator when 
> you are not modifying the contents of a container. Personally 
> I struggled with the idea of const for years.  I think it is 
> just one more helpful tool to make life easier and you do it 
> when you can.
> 
> o) Prefer comparing iterators with != , not <.  The book 
> mentions that this is allowed for all iterators so it is easy 
> to change containers.  
> However, as stated in Effective STL, it might be more 
> complicated than just != to switch containers in the code and 
> it might be too costly to keep that avenue open.  But != is a 
> easy price to pay, it works for everyone.
> 
> o)  Get in the habit of using the prefix forms of -- and ++ 
> by default, unless you really need the old value.
> 
> o) Practice reuse:  Prefer reusing existing algorithms, 
> particularly standard algorithms (e.g. for_each) instead of 
> crafting your own loops.  
> Reuse might prevent the possibility of introducing more 
> errors like prefix forms, != etc.
> 
> I hope I covered the major points.

Tim,

you did a great job.  It and this discussion certainly set the bar fairly
high.

I would like to add to the summary two bits that have been overlooked up to
now.

4. (p. 6) avoid unecessary recalculations.  This is pertinent in a for loop.
If the for loop has this structure:

for (vector<int>::const_iterator it = vint.begin(); it != vint.end(); ++ it
)

the value of vint.end() has to be calculated each time through the loop.  On
small vectors this would have no appreciable effect, but for very large
vectors, and I would guess for vectors of fairly complicated data
structures, the overhead of this recalculation could be quite significant.
I like the advice to calculate the value of vint.end() once outside the body
of the loop, and use that constant value for the terminal point of the loop.
(though, physician 'heal thyself' would be appropriate here, since I always
turn to the less efficient manner in my own code -- since my fingers almost
automatically key the code in :) .

5. (p. 7) prefer '\n' to endl.  On some systems, the overhead of calling
endl can be significant. In addition, in web applications, where probably
75% of the code involves writing output to the web browser, using '\n' can
dramatically improve response times.

Anyway, small points, but I didn't want them to get overlooked in our
discussion.

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