May 17, 2012

array vs vector

Every beginner is struggling doing something that is so simple to others.

Once you know it, you will say to yourself: I did know it should be something simple like this.

Specify the size of array at run-time,dynamically

in C++, sometimes(for me, most of the times), we don't know how long should an array should be. If that is the case, we can do the following:

float *pTable;
int n = 100;
pTable = new float[n];

The point is that one of the common use of pointer is to allocate memory in leap . Then at run-run, you can choose the size based on the need. But once you use new, don't forget to use delete to free the memory.
delete [ ] pTable;

And notice that we also have a STL container called std::array, (include it with #include<array>), it adds useful member functions and iterators to it. So it convenient to use. But still, you need to use pointer to get a run-time specified size of it.
OK, now we see that the built-in array have some drawbacks and even for the std::array we have to specify the size of it with a constant. Why don't we just use vector, which does all the tedious work for us? "I thought for a computation intense program, array is faster than vector," you will think like this as I did. However, this is not true!
Read this link for this answer then you will not waste you time in figuring out those tedious things related to array, just go with vector and finish your work.

Then here is the conclusion: just go with vector


  1. Nearly all of the time, you should choose vector instead of array( built-in or std::array). Spend those saved time in programming.
  2. the vector performs less efficient only when you need change its size frequently(which makes it reallocate the memory). If that's not the case, their performance almost the same.
  3. the compile spends a lot of extra work in range-checking or similar thing in debugging. Once you got your program right, you can use a optimized build and right settings (removing the STL debugging).


No comments: