Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of using arrays instead of std::vector?

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

like image 558
MOnsDaR Avatar asked Oct 23 '10 12:10

MOnsDaR


2 Answers

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 desirable.
  • 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).
  • Fixed-size arrays can be embedded directly into a struct or object, which can improve memory locality and reducing the number of heap allocations needed.
like image 121
Mr Fooz Avatar answered Oct 20 '22 09:10

Mr Fooz


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');
...
like image 33
Alex Jasmin Avatar answered Oct 20 '22 09:10

Alex Jasmin