[LC++]STL vector push_back() and resize()
Torsten Rennett
Torsten at Rennett.de
Thu Sep 6 21:03:39 UTC 2001
Mark Phillips wrote:
>
> Suppose I want a vector with the i-th element being i squared.
>
> One way to do it would be as follows:
>
> vector<int> vec;
> for (int i=0; i<10; i++)
> vec.push_back(i*i);
>
> Another way of doing it would be:
>
> vector<int> vec;
> vec.resize(10);
> for (int i=0; i<10; i++)
> vec[i]=i*i;
>
> Do both these methods end up with the same final result, or does
> the first method end up allocating more memory than it needs?
Yes, that's right, it depends on the actual implementation.
> Also, is one method more efficient than the other?
The first one may reallocate and the second calls the default ctor
which is not necessary, but not too bad for ints ;-) ...
I think the fastes would be to use reserve() instead of resize():
vector<int> vec;
vec.reserve(10);
for (int i=0; i<10; i++)
vec.push_back(i*i);
This prevents reallocating and no default ctor is called.
Or to give the needed size in the ctor:
vector<int> vec(10);
for (int i=0; i<10; i++)
vec[i]=i*i;
> Final question. If I do:
>
> vector<int> vec;
> vec.resize(10);
> for (int i=0; i<10; i++)
> vec.push_back(i*i);
>
> does this give me the wrong result. Ie does it create a vector
> with 20 elements in it?
Just test it!
for (vector<int>::const_iterator it = vec.begin();
it != vec.end();
++it)
clog << *it << endl;
(I guess you'll get 20 elements, with the first 10 all 0.)
> I think there are a few technicalities with the STL vector class
> that I don't understand properly.
I can highly recommend the following book as tutorial and reference:
Nicolai M. Josuttis:
The C++ Standard Library: A Tutorial and Reference
ISBN: 0-201-37926-0
http://www.josuttis.com/libbook/index.html
http://cseng.aw.com/book/0,3828,0201379260,00.html
Josuttis is an active member of the C++ Standard Committee library
working group.
And from the same author there is also a rather new book about learning
C++:
In german:
Objektorientiertes Programmieren in C++
Ein Tutorial für Ein- und Umsteiger
Addison-Wesley Germany, 2001
ISBN 3-8273-1771-1
http://www.josuttis.com/cppbuch/index.html
In english (coming soon):
Object-Oriented Programming in C++
http://www.josuttis.com/cppbook/index.html
I found this the best books on the topic I've ever seen.
Have a look on the listed web pages for other comments.
Torsten
--
Ingenieurbuero RENNETT -- innovative Individual-Software --
Torsten Rennett
Ludwig-Thoma-Weg 14 E-Mail: mailto:Torsten at Rennett.de
D-85551 Heimstetten Telefon: +49-89-90480538
More information about the tuxCPProgramming
mailing list