382

What are the difference between a std::vector and an std::array in C++? When should one be preferred over another? What are the pros and cons of each? All my textbook does is list how they are the same.

Martin G
  • 17,357
  • 9
  • 82
  • 98
Zud
  • 4,247
  • 4
  • 24
  • 25
  • 2
    I'm looking for a comparison of `std::vector` vs. `std::array` and how the terms are different. – Zud Dec 12 '10 at 23:02
  • 1
    Zud, `std::array` is not the same as a C++ array. `std::array` is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class. I will update my answer. – ClosureCowboy Dec 12 '10 at 23:19
  • I updated the question title and text to reflect your clarification. – Matteo Italia Dec 12 '10 at 23:32
  • If you are implementing constexpr or consteval function then you can use std::array, but can't use std::vector https://stackoverflow.com/questions/33241909/cannot-create-constexpr-stdvector – Anton Krug Apr 10 '21 at 16:48

6 Answers6

399

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.
Helmster
  • 15
  • 5
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • 8
    Regarding your footnote: While true, the standard also guarentees that pointer arithmetic on the internal elements works, which means that it does have to be an array: &vec[9] - &vec[3] == 6 is true. – Lucretiel Mar 12 '12 at 06:17
  • 11
    I'm pretty sure, that vector doesn't shrink automatically, but since C++11 you can call shrink_to_fit. – Dino Sep 09 '14 at 09:24
  • 1
    I'm totally confused by the term _static array_ and I'm not sure what the right terminology is. You mean a static size array and not an static variable array (one using static storage). https://stackoverflow.com/questions/2672085/c-static-array-vs-dynamic-array/26466627#26466627. What is the correct terminology? Is static array a sloppy term for an array with a fixed size? – Z boson Oct 21 '14 at 11:30
  • @Zboson: I mean a statically-*sized* array; sorry, I agree that the terminology is confusing, I'll fix it immediately. – Matteo Italia Oct 21 '14 at 11:55
  • @MatteoItalia, okay, so it's not just me. I'm not trying to be pedantic. It's just that I read a x86 assembly manual recently and it used a static array as one defined in the data/BSS section but it seems on SO most questions/answers assume a static array is an automatic variable array. – Z boson Oct 21 '14 at 12:25
  • 5
    @Zboson: it's definitely not just you, *static* is quite an abused term; the very `static` keyword in C++ has three different unrelated meanings, and the term is also used often to talk about stuff that is fixed at compile time. I hope that "statically-sized" is a bit more clear. – Matteo Italia Oct 21 '14 at 12:55
  • 1
    @Dino, `std::shrink_to_fit` does not guarantee a shrinking, it may shrink the vector, but it's not 100% guaranteed. – vsoftco Dec 20 '14 at 04:30
  • would performance of vector be comparable to array if both are on the heap? – johnbakers Jun 27 '16 at 16:54
  • 4
    One thing to note: For real-time programming (where you aren't supposed to have **any** dynamic allocation/deallocation after startup) std::array would probably be preferred over std::vector. – T.E.D. Jan 13 '17 at 15:20
  • I cannot figure out how the [bench-mark](http://quick-bench.com/wOn8IPnv4DxsicBwacFZJsJNjuw) shows opposite. – ar2015 Sep 30 '18 at 05:04
  • 1
    @ar2015 May be because in the example, the vector is not resized dynamically? – talekeDskobeDa Oct 21 '19 at 14:19
  • @T.E.D. You could also use std::vector with a custom allocator, which might be a better option than std::array eating the stack. – marski Mar 15 '20 at 15:08
  • 1
    Thank you for the nice and comprehensive answer! What do you mean by saying: "but it's often more efficient, especially for small sizes". Why do you think efficiency gains are diminished with larger sizes? What would you classify as small sized ? – fabian Mar 24 '21 at 08:57
  • 1
    @fabian indeed that statement isn't very precise... the general idea is that (at first approximation) we can imagine the cost of a dynamic allocation as roughly fixed, but for big sizes generally it's going to be dwarfed by the computation you are going to do on the memory. OTOH, for a small scratch buffer that is going just as temporary storage it may become the dominant cost. Also, doing a ton of small allocs/deallocs generally hurts the overall performance of the allocator (if not tuned specifically for it), so it's something you often want to avoid if possible. – Matteo Italia Mar 24 '21 at 16:13
29

To emphasize a point made by @MatteoItalia, the efficiency difference is where the data is stored. Heap memory (required with vector) requires a call to the system to allocate memory and this can be expensive if you are counting cycles. Stack memory (possible for array) is virtually "zero-overhead" in terms of time, because the memory is allocated by just adjusting the stack pointer and it is done just once on entry to a function. The stack also avoids memory fragmentation. To be sure, std::array won't always be on the stack; it depends on where you allocate it, but it will still involve one less memory allocation from the heap compared to vector. If you have a

  • small "array" (under 100 elements say) - (a typical stack is about 8MB, so don't allocate more than a few KB on the stack or less if your code is recursive)
  • the size will be fixed
  • the lifetime is in the function scope (or is a member value with the same lifetime as the parent class)
  • you are counting cycles,

definitely use a std::array over a vector. If any of those requirements is not true, then use a std::vector.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
26

Summarizing the above discussion in a table for quick reference:

C-Style Array std::array std::vector
Size Fixed/Static Fixed/Static Dynamic
Memory efficiency More efficient More Efficient Less efficient
(May double its size on new allocation.)
Copying Iterate over elements
or use std::copy()
Direct copy: a2 = a1; Direct copy: v2 = v1;
Passing to function Passed by pointer.
(Size not available in function)
Passed by value Passed by value
(Size available in that function)
Size sizeof(a1) / sizeof(a1[0]) a1.size() v1.size()
Use case For quick access and when
insertions/deletions not frequently needed.
Same as classic array but
safer and easier to pass and copy.
When frequent additions or
deletions might be needed
Frida Schenker
  • 1,219
  • 1
  • 9
  • 14
  • `void foo(T (& arr)[N])` would capture array size. similar [magic-arguments-in-function-templates](https://stackoverflow.com/questions/2384107/magic-arguments-in-function-templates) – I.Omar Nov 14 '21 at 18:22
  • I would add these rows: "| Value semantics | no | yes | yes |" and "| Move | O(N) | O(N) | O(1) |" and "| Swap | O(N) | O(N) | O(1) |" – alfC Feb 01 '22 at 19:11
  • What exactly is "Memory efficiency"? The expression can be ambiguous. Also, how the capacity of `std::vector` gets increased on new allocation *depends on implementation*. E.g. MSVC increases the capacity by x1.5, not x2. – starriet Aug 20 '22 at 06:44
24

If you are considering using multidimensional arrays, then there is one additional difference between std::array and std::vector. A multidimensional std::array will have the elements packed in memory in all dimensions, just as a C style array is. A multidimensional std::vector will not be packed in all dimensions.

Given the following declarations:

int cConc[3][5];
std::array<std::array<int, 5>, 3> aConc;
int **ptrConc; // initialized to [3][5] via new and destructed via delete
std::vector<std::vector<int>> vConc; // initialized to [3][5]

A pointer to the first element in the C-style array (cConc) or the std::array (aConc) can be iterated through the entire array by adding 1 to each preceding element. They are tightly packed.

A pointer to the first element in the vector array (vConc) or the pointer array (ptrConc) can only be iterated through the first 5 (in this case) elements, and then there are 12 bytes (on my system) of overhead for the next vector.

This means that a std::vector<std::vector<int>> array initialized as a [3][1000] array will be much smaller in memory than one initialized as a [1000][3] array, and both will be larger in memory than a std::array allocated either way.

This also means that you can't simply pass a multidimensional vector (or pointer) array to, say, OpenGL without accounting for the memory overhead, but you can naively pass a multidimensional std::array to OpenGL and have it work out.

Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
psimpson
  • 406
  • 4
  • 11
20

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>:

  1. 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.

  2. 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 bools!

  3. 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.

ClosureCowboy
  • 20,825
  • 13
  • 57
  • 71
  • 8
    It's 'just as fast" as using a dynamically-allocated built-in array. On the other hand, using an automatic array might have considerably different performance (and not only during allocation, because of locality effects). – Ben Voigt Aug 27 '13 at 18:13
  • 8
    For non-bool vectors in C++11 and later, you can call `data()` on a `std::vector` to get the underlying pointer. You can also just take the address of element 0 (guaranteed to work with C++11, will probably work with earlier versions). – Matt Jun 25 '15 at 18:01
  • 1
    In last paragraph you mean C array ? Right ? – 0xB00B Jun 18 '21 at 08:53
-20

A vector is a container class while an array is an allocated memory.

Saif al Harthi
  • 2,948
  • 1
  • 21
  • 26
  • 27
    Your answer seems to address `std::vector` versus `T[]`, but the question is about `std::vector` versus `std::array`. – Keith Pinson Jan 23 '13 at 16:36