Search⌘ K
AI Features

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.

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.

Vector with indices
Vector with indices

Goal

You’ll aim to:

  • Use vector to 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.

C++
#include <iostream>
#include <vector> // For using the vector container
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3}; // Declares a vector and initializes it with 3 integers
numbers.push_back(4); // Adds 4 to the end of the vector
cout << numbers[3] << endl; // Prints the 4th element in the vector (index 3)
return 0;
}

push_back() adds elements dynamically.

Updating a vector with push.back ( )
Updating a vector with push.back ( )

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():

C++
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3};
cout << "Vector (before push_back()): ";
for (int i = 0; i < numbers.size(); i++) { // Loops through the vector using its size
cout << numbers[i] << " "; // Prints each number in the vector before push.back()
}
numbers.push_back(4); // Add item
cout << endl << "Vector (after push_back()): ";
for (int i = 0; i < numbers.size(); i++) { // Loops through the vector using its size
cout << numbers[i] << " "; // Prints each number in the vector after push.back()
}
return 0;
}

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