[Exceptional C++ Style] Item 26 -- Data Formats and Efficiency
Kloss, Burkhard (IT)
Burkhard.Kloss at morganstanley.com
Mon Jan 31 09:45:24 EST 2005
Lois,
> Solutions
> 1. Each kind of container in the standard C++ library chooses
> a different trade-off of space vs performance.
>
> - A vector<T> stores T objects in a contiguous array and so
> has no per-element overhead at all.
That is if the vector's capacity is the same as its size. If you grow a
vector with push_back, you can actually have an overhead of a 100% at
times because the vector doubles its internal memory allocation when it
reallocates.
vector <double> v;
for (int i = 0; i < 200; ++i)
{
cout << i << ", " << v.size () << ", " << v.capacity () << "\n";
v.push_back (i);
}
==>
0, 0, 0
1, 1, 1
2, 2, 2
3, 3, 4
4, 4, 4
5, 5, 8
6, 6, 8
7, 7, 8
8, 8, 8
9, 9, 16
etc.
Just a minor point, but worth bearing in mind. Depending on your
situation, it might be better to pre-allocate the capacity in the vector
first.
Burkhard
--------------------------------------------------------
NOTICE: If received in error, please destroy and notify sender. Sender does not waive confidentiality or privilege, and use is prohibited.
More information about the Effective-cpp
mailing list