[ACCEPTED]-Advantages of using arrays instead of std::vector?-vector

Accepted answer
Score: 13

In general, I strongly prefer using a vector 2 over an array for non-trivial work; however, there 1 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.
Score: 6

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

Compared to array initialization:

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

vector 1 initialization can look somewhat verbose

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

I'd go for std::array available in C++0x 3 instead of plain arrays which can also be 2 initialized like standard arrays with an 1 initializer list

https://en.cppreference.com/w/cpp/container/array

Score: 1

I think this is because a lot of C++ programmers 3 come from C and don't yet understand the 2 advantages of using vector and all the extra STL 1 goodies that come for free with its containers.

Score: 1

You have much more control with arrays

How 22 about:

1) you are dealing with colossal data 21 sets where the data has to be mapped files 20 and not allocated with malloc or new because of its 19 size. Under this scenario worrying about 18 what to do if you didn't reserve enough 17 address space at the beginning may be moot, though 16 I suppose you could unmap - extend - remap 15 the file, unless prohibited by address fragmentation 14 or my second point.

2) Code that uses lockless 13 multiprocessing. Performance hits of stopping 12 the threads for re-allocation (or any other 11 "STL goodie") may be unacceptable, hence 10 use arrays, you have got much more control, you 9 may need to call a lot of functions to pause 8 other threads before you resize anything.

BTW, I'm 7 usually dealing with 1 and 2 at the same 6 time. Arrays of structures + pointers work 5 wonderfully, Compiling with C++ because 4 you you can still use some C++ features 3 elsewhere in the code. I'm sure I could 2 think of many more examples if I tried hard 1 enough

More Related questions