Using the std::vector<T>
class:
...is just as fast as using built-in arrays, assuming you are doing only the things built-in arrays allow you to do (read and write to existing elements).
...automatically resizes when new elements are inserted.
...allows you to insert new elements at the beginning or in the middle of the vector, automatically "shifting" the rest of the elements "up"( does that make sense?). It allows you to remove elements anywhere in the std::vector
, too, automatically shifting the rest of the elements down.
...allows you to perform a range-checked read with the at()
method (you can always use the indexers []
if you don't want this check to be performed).
There are two three main caveats to using std::vector<T>
:
You don't have reliable access to the underlying pointer, which may be an issue if you are dealing with third-party functions that demand the address of an array.
The std::vector<bool>
class is silly. It's implemented as a condensed bitfield, not as an array. Avoid it if you want an array of bool
s!
During usage, std::vector<T>
s are going to be a bit larger than a C++ array with the same number of elements. This is because they need to keep track of a small amount of other information, such as their current size, and because whenever std::vector<T>
s resize, they reserve more space then they need. This is to prevent them from having to resize every time a new element is inserted. This behavior can be changed by providing a custom allocator
, but I never felt the need to do that!
Edit: After reading Zud's reply to the question, I felt I should add this:
The std::array<T>
class is not the same as a C++ array. std::array<T>
is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class (in C++, arrays are implicitly cast as pointers, often to dismaying effect). The std::array<T>
class also stores its size (length), which can be very useful.