Advantages of using arrays instead of std::vector?

2019-01-14 13:40发布

问题:

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

回答1:

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


回答2:

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


回答3:

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



回答4:

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.



回答5:

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 or new 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