Track with Vectors
Explore how to use dynamic vectors in C++ to manage flexible data lists. Learn to create, add, remove, and access elements, compare vectors with arrays, and iterate through vectors using loops to build smarter, adaptable code.
We'll cover the following...
You’ve used fixed-size arrays. Now let’s upgrade to dynamic containers: vector. Vectors let you add, remove, and manage data on the fly.
Goal
You’ll aim to:
Use
vectorto store flexible lists.Add, access, and loop through items.
Compare with arrays.
Include the vector library
#include <vector>
Always include it at the top.
Create and initialize a vector
We can create a vector in C++ and initialize it with starting values. After that, we can still add more elements when needed.
push_back() adds elements dynamically.
Iterate through a vector
Let’s iterate through a vector in C++ using a for loop and indexing, and see how the vector looks before and after we update it using push_back():
You’ve looped through dynamic data.
This is one common way to iterate through a vector using a traditional for loop and indexing.
Vector features
Grows and shrinks automatically.
.size()returns the current length.push_back(),pop_back()= add/remove