I'm currently seeing a lot of questions which are tagged C++ and are about handling arrays.
There even are questions which ask about methods/features for arrays which a std::vector
would provide without any magic.
So I'm wondering why so much developers are chosing arrays over std::vector
in C++?
In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays.
Because C++03 has no vector literals. Using arrays can sometime produce more succinct code.
Compared to array initialization:
vector initialization can look somewhat verbose
I think this is because a lot of C++ programmers come from C and don't yet understand the advantages of using
vector
and all the extra STL goodies that come for free with its containers.You have much more control with arrays
How about:
1) you are dealing with colossal data sets where the data has to be mapped files and not allocated with
malloc
ornew
because of it's size. Under this scenario worrying about what to do if you didn't reserve enough address space at the beginning may be moot, though I suppose you could unmap - extend - remap the file, unless prohibited by address fragmentation or my second point.2) Code that uses lockless multiprocessing. Performance hits of stopping the threads for re-allocation (or any other "STL goodie") may be unacceptable, hence use arrays, you have got much more control, you may need to call a lot of functions to pause other threads before you resize anything.
BTW, I'm usually dealing with 1 and 2 at the same time. Arrays of structures + pointers work wonderfully, Compiling with C++ because you you can still use some C++ features elsewhere in the code. I'm sure I could think of many more examples if I tried hard enough
I'd go for std::array available in C++0x instead of plain arrays which can also be initialized like standard arrays with an initializer list
http://www2.research.att.com/~bs/C++0xFAQ.html#std-array