What are the differences between an array and a vector in C++? An example of the differences might be included libraries, symbolism, abilities, etc.
Arrays contain a specific number of elements of a particular type. So that the compiler can reserve the required amount of space when the program is compiled, you must specify the type and number of elements that the array will contain when it is defined. The compiler must be able to determine this value when the program is compiled. Once an array has been defined, you use the identifier for the array along with an index to access specific elements of the array. [...] arrays are zero-indexed; that is, the first element is at index 0. This indexing scheme is indicative of the close relationship in C++ between pointers and arrays and the rules that the language defines for pointer arithmetic.
— C++ Pocket Reference
A vector is a dynamically-sized sequence of objects that provides array-style
operator[]
random access. The member functionpush_back
copies its arguments via copy constructor, adds that copy as the last item in the vector and increments its size by one.pop_back
does the exact opposite, by removing the last element. Inserting or deleting items from the end of a vector takes amortized constant time, and inserting or deleting from any other location takes linear time. These are the basics of vectors. There is a lot more to them. In most cases, a vector should be your first choice over a C-style array. First of all, they are dynamically sized, which means they can grow as needed. You don't have to do all sorts of research to figure out an optimal static size, as in the case of C arrays; a vector grows as needed, and it can be resized larger or smaller manually if you need to. Second, vectors offer bounds checking with theat
member function (but not withoperator[]
), so that you can do something if you reference a nonexistent index instead of simply watching your program crash or worse, continuing execution with corrupt data.— C++ Cookbook
arrays:
malloc
);sizeof
(hence the common idiom sizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer);std::vector
:
&vec[0]
is guaranteed to work as expected);begin()
/end()
methods, the usual STL typedef
s, ...)Also consider the "modern alternative" to arrays - std::array
; I already described in another answer the difference between std::vector
and std::array
, you may want to have a look at it.