Learn C++ 4: std::array vs std::vector
std::array
and std::vector
are both container classes provided by the C++ Standard Library, but they have different characteristics and are used for different purposes:
- Size:
-
std::array
: Has a fixed size determined at compile time, specified by its template parameter. Once created, the size of astd::array
cannot be changed. -
std::vector
: Has a dynamic size that can grow or shrink at runtime. Elements can be added or removed from astd::vector
after it’s created.
-
- Memory Allocation:
-
std::array
: Typically allocated on the stack. The size of astd::array
must be known at compile time, so its memory is allocated statically. -
std::vector
: Typically allocated on the heap. The memory for astd::vector
is dynamically allocated, allowing it to resize as needed.
-
- Accessing Elements:
-
std::array
: Supports constant time (O(1)) random access to elements using the[]
operator. It provides efficient access to elements since the array is contiguous in memory. -
std::vector
: Supports constant time (O(1)) random access to elements using the[]
operator. Likestd::array
, it provides efficient access to elements due to its contiguous memory layout.
-
- Performance:
-
std::array
: Typically offers better performance thanstd::vector
for small, fixed-size collections because of its static memory allocation and lack of dynamic resizing overhead. -
std::vector
: Offers better performance for large collections or when the size of the collection is unknown at compile time, as it can dynamically resize itself to accommodate new elements.
-
- Usage:
-
std::array
: Useful when the size of the collection is known at compile time and does not change. It’s often used for small, fixed-size collections where the size is known in advance. -
std::vector
: Suitable when the size of the collection can change dynamically at runtime or when the size is not known at compile time. It’s a versatile container that can be resized and is widely used in C++.
-
In summary, choose std::array
when you need a fixed-size container with known size at compile time, and choose std::vector
when you need a dynamic-size container or when the size is not known at compile time.
Enjoy Reading This Article?
Here are some more articles you might like to read next: