Welcome! Today's lesson focuses on vectors, which are dynamic equivalents of arrays in C++. We'll discuss how to declare, initialize, access, and manipulate them, and we'll delve into other unique elements.
Vectors are dynamic arrays that form part of the C++ Standard Library. Unlike arrays, which require a pre-defined size, vectors allow elements to be populated as needed, resizing as they grow.
To use vectors, you must include the vector library:
This library provides the necessary functionality to work with vectors.
Vectors are declared using the std::vector
template followed by the type of elements they will store. Here's the anatomy of a vector declaration:
You can use the following options to initialize a vector:
- Static vs. Dynamic Size: Arrays have a fixed size declared at compile time. Vectors can grow and shrink dynamically as elements are added or removed.
- Memory Management: Arrays have contiguous memory allocation. Vectors handle memory automatically, resizing and managing space as needed.
