[Effective-cpp] Vector Capacity and Size

Adrian Fagg AdrianF at evaluategroup.com
Mon Dec 1 04:17:03 EST 2003


> -----Original Message-----
> From: Carol/Matthew Schroeder [mailto:bigoldog at earthlink.net]
> Sent: 30 November 2003 22:04

> Sorry if this is a bit off topic for item 19, but I was
> looking at solutions for the Linux/STL group.

Fine by me - this relates to one of the earlier items in any case...

> 
> My preferred method is method 2. I originally wrote 
>...
>   int raw_data[] = { 1, 2, 3, 4, 5 };
> 
>   std::vector<int> const test_vector(
> 
>           raw_data,
> 
>           raw_data + sizeof(raw_data) / sizeof(raw_data[0]));
> 
>...

I agree with the above, even though as you say, no guarantees of the
capacity are made.
For that constructor in general, the iterators passed might not have the
traits of the one that you're using, so the implied repeated push_back
internally would be necessary for the general case.
However, the implementers presumably have the opportunity to specialise for
the above case, where the desired capacity can be determined initially.

Apart from that, these observations that come to mind:

Firstly, you should certainly try to give the best chance of efficient
allocations where possible.

Secondly, don't worry about what the implementation actually does - if it
chooses to make a couple of allocations in the above constructor and end up
with a capacity of 23, just shrug your shoulders...

Thirdly, consider avoiding the above code altogether! That is, the most
likely real world use of such a vector is as a constant - so either use the
constant array (that probably should be const too and the iterators could be
made available through functions) or if you must use the vector, make that a
const.

Regards,

Adrian

Work: mailto:adrianf at evaluategroup.com
Home: mailto:adrian.fagg at ntlworld.com

Pretty pictures: http://homepage.ntlworld.com/rbyadf/ 
[ *** LongSig auto truncated *** ]

--- StripMime Report -- processed MIME parts ---
multipart/alternative
  text/plain (text body -- kept)
---



More information about the Effective-cpp mailing list