I think this question is best answered flipped around:
What advantages does std::vector
have over raw arrays?
I think this list is more easily enumerable (not to say this list is comprehensive):
- Automatic dynamic memory allocation
- Proper
stack
, queue
, and sort
implementations attached
- Integration with C++ 11 related syntactical features such as
iterator
If you aren't using such features there's not any particular benefit to std::vector
over a "raw array" (though, similarly, in most cases the downsides are negligible).
Despite me saying this, for typical user applications (i.e. running on windows/unix desktop platforms) std::vector
or std::array
is (probably) typically the preferred data structure because even if you don't need all these features everywhere, if you're already using std::vector
anywhere else you may as well keep your data types consistent so your code is easier to maintain.
However, since at the core std::vector
simply adds functionality on top of "raw arrays" I think it's important to understand how arrays work in order to be fully take advantage of std::vector
or std::array
(knowing when to use std::array
being one example) so you can reduce the "carbon footprint" of std::vector
.
Additionally, be aware that you are going to see raw arrays when working with
- Embedded code
- Kernel code
- Signal processing code
- Cache efficient matrix implementations
- Code dealing with very large data sets
- Any other code where performance really matters
The lesson shouldn't be to freak out and say "must std::vector
all the things!" when you encounter this in the real world.
Also: THIS!!!!
- One of the powerful features of C++ is that often you can write a class (or struct) that exactly models the memory layout required by a specific protocol, then aim a class-pointer at the memory you need to work with to conveniently interpret or assign values. For better or worse, many such protocols often embed small fixed sized arrays.
- There's a decades-old hack for putting an array of 1 element (or even 0 if your compiler allows it as an extension) at the end of a struct/class, aiming a pointer to the struct type at some larger data area, and accessing array elements off the end of the struct based on prior knowledge of the memory availability and content (if reading before writing) - see What's the need of array with zero elements?
- embedding arrays can localise memory access requirement, improving cache hits and therefore performance