[LC++]STL vector push_back() and resize()

Mark Phillips mark at austrics.com.au
Thu Sep 6 12:30:05 UTC 2001


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?

Also, is one method more efficient than the other?


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?

I think there are a few technicalities with the STL vector class
that I don't understand properly.

Cheers,

Mark.



More information about the tuxCPProgramming mailing list