Jim Langston said:
No. It is unspecified behavior either way. reserve will
allocate memory to extend the size of an array, but it does
not actually grow the size. resize() will both allocate the
memory and extend the size also.
Note, that changing vec[jj] = jj;
to vec.push_back( jj );
would mean you don't need resize or reserve. However, if you
know before hand how much memory you are going to need, how
many elements, you may wish to resize it to avoid needless
calls to new.
Hmm, I would frown on the gratuitous use of resize()
If you're going to use [] on the elements afterwards, it's not
gratuitous
.
OK but more important if en is large.
For a sufficient definition of large. In practice, I've never
really found it to make a measurable difference. But then, I
don't construct vectors with millions of elements which are
expensive to copy. Which brings up the second point: it's more
important if the elements are expensive to copy.
// And initialise all elements !
for (int jj = 0; jj < en; ++jj)
vec[jj] = jj;
Yes, you do avoid reallocating of the vector buffer however,
vec.resize() will default initialize all elements in the
vector. This is likely to be much more expensive than using
reserve() or even what you would have to pay for using
push_back() directly without pre-reserving anything.
That's what I would have thought, too. Measurements with
vector<int> and vector<double>, on the other hand, show the
resize version to be considerably faster. On a Sparc, at least:
I just reran a benchmark, and found the version with resize
faster on Sparc, but the version with push_back and reserve
faster on a PC under Linux (both compiled with g++, using the
same options: -std=c++98 -pedantic -ffor-scope -fno-gnu-keywords
-foperator-names -pipe -Wall -W -Wno-sign-compare
-Wno-deprecated -Wno-non-virtual-dtor -Wpointer-arith
-Wno-unused -Wno-switch -Wno-missing-braces -Wno-long-long
-static-libgcc -O3 -fomit-frame-pointer -finline-functions
I'd still use push_back in this case; it seems more idiomatic.
And at the first sign of a performance problem, I'd slip in a
reserve (although I certainly wouldn't bother with it until
there was a performance problem).