I've just learned how to use vectors.

I'm thinking about, what is the best way to create a vector, IF you do not know its initial size. Here are some of my options.

1.)
This is the simplest I think, but is there any memory issue about this technique?

vector<myObject> myVector;

  int size = 5;
  myVector = vector<myObject>(size);

2.) Just like number 1 , but using pointer.

vector<myObject>* myVector;
  
   int size = 5;
   myVector = &(vector<myObject>(size));

3.)

vector <myObject> myVector;
  
  int size = 5;
  for (int i = 0; i < size ; i++) {
      myVector.push_back( myObject() );
  }

I would like to know your comments about these 3 ways, their advantages and disadvantages in terms of memory I think, or performance. Thank you very much!!!

Edited 6 Years Ago by macobex: n/a

It depends. There is no one best way to initialize a vector and the method you choose should fit the problem at hand. However, if efficiency is something which you want to place priority on, you should consider some of the other container types that are available.

A vector uses an array to store its values, so when the array is used up, it must copy everything in that array into a new array in order to add more data, and this can definitely slow things down a bit. The advantage of this though is that data access is very fast.

Some alternatives are linked lists, sets and maps. These use totally different strategies for data storage and retrieval which can vastly change performance depending on how you use them. Lists for example are much more efficient for storing data, but much less efficient in data retrieval.

Edited 6 Years Ago by Sumyungi: n/a

push_back triggers memory reallocation when the size of the vector becomes greater than the capacity(the memory is copied into a larger one - twice as large to be precise). If you know it's size, simply resize it, but push back can do no harm.

Tip!
If you want to shrink the vector to hold only it's size use this:

vector <int> tempVector(myVector).swap (MyVector);
This article has been dead for over six months. Start a new discussion instead.