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.

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));


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!!!

Recommended Answers

All 3 Replies

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.

I never create a pointer to a vector -- pointer here is just not necessary. Your third example is the most common way to do it.

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.

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

vector <int> tempVector(myVector).swap (MyVector);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.