views:

151

answers:

4

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++?

+5  A: 

In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays.

  • arrays are slightly more compact: the size is implicit
  • arrays are non-resizable; sometimes this is desireable
  • arrays don't require parsing extra STL headers (compile time)
  • it can be easier to interact with straight-C code with an array (e.g. if C is allocating and C++ is using)
Mr Fooz
Also: * arrays are faster; * arrays can be initialized statically (while vectors are always initialized dynamically, at run time)
mojuba
Alas the reason that "so much developers are chosing arrays over std::vector in C++" is just because they read some old/bad books and now are reluctant to switch to a new level of programming. I doubt many even consider any of your points before deciding using arrays. Also no matter what vector provides, any programmer must theoretically be able to use arrays, because if you don't understand pointers and their arithmetic you can't be a good c++ programmer
Armen Tsirunyan
+3  A: 

Because C++03 has no vector literals. Using arrays can sometime produce more succinct code.

Compared to array initialization:

char arr[4] = {'A', 'B', 'C', 'D'};

vector initialization can look somewhat verbose

std::vector<char> v;
v.push_back('A');
v.push_back('B');
...
Alexandre Jasmin
+2  A: 

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

David
+1  A: 

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.

Steve Townsend
You may be right. But you can still use some of the extra goodies (STL algorithms) with arrays.
Alexandre Jasmin