Loading lessons...
Introduction to Containers and Arrays
Introduction to Containers and Arrays
What is a container?
A container is an object that holds other objects - a collection of values stored together. Containers let you add items, count them, read them by index, and walk through them. There are many kinds; the one we start with is the array.
Arrays: the first container
An array is a container that stores several objects of the same type in a row in memory. It's the classic base container: simple, fast, and the foundation for many others.
C++ gives you two families of arrays:
- Built-in (C-style) arrays like
int arr[3]. Fixed size decided at compile time, and little else - no self-knowledge of size, no bounds checks. - Library arrays like
std::vector, which wrap the idea with convenience: they know their size, check bounds, and grow automatically.
std::vector vs built-in arrays
std::vector is the modern workhorse: its size can change while the program runs, and it keeps track of how many elements it has. A built-in array is stuck at the size you declared, and it can decay into a pointer when passed around (more on that later).
The modern rule
In almost all new C++ code, reach for std::vector (dynamic) or std::array (fixed size) instead of raw built-in arrays. Built-in arrays still exist and still work, but the library types are safer and just as fast.
TL;DR
- A container is an object that holds other objects.
- Arrays are the base container of C++: same-type values in a row.
- Built-in arrays have a fixed compile-time size and little help.
std::vectorknows its size and can grow and shrink.- Prefer
std::array/std::vectorover raw built-in arrays.