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.
- Functionality: Vectors provide built-in functions like
push_back()
,pop_back()
,insert()
,erase()
, etc., which are not available for arrays.
Like arrays, vectors store elements in contiguous storage locations, allowing efficient access using indices. Elements can be accessed like array elements (vector[index]
). Indices can also be used to modify vector values.
Let's demonstrate how to initialize and modify values:
Vectors support several built-in operations, including size()
, empty()
, clear()
. These operations streamline the process of working with vectors.
Let's demonstrate a few of these operations:
- size(): Returns the number of elements in the vector.
- empty(): Checks whether the vector is empty or not.
- clear(): Removes all elements from the vector.
The push_back()
function appends elements to the end of the vector, allowing us to populate an uninitialized vector.
The pop_back()
function removes the last element of the vector.
Similar to arrays, we can traverse a vector to access or modify its elements using a for
loop. A more modern and concise approach is using the range-based for
loop, which eliminates the need for explicitly iterating through array indexes:
Vectors in C++ are type-safe, meaning they can only store elements of a single data type. Attempting to use mixed data types will result in a compile-time error:
Congratulations! You have traversed the fundamentals of vectors in C++. Up next are practice exercises designed to instill your understanding of vectors in C++. Enjoy these engaging exercises!
