Python Dynamic Arrays: std::vector and STL
Fixed arrays are restrictive because you must know their exact size in advance. The Standard Template Library (STL) provides std::vector—a dynamic array that automatically grows and shrinks as you add or remove elements.
"If a fixed array is an unexpandable wooden egg carton with 6 slots, a std::vector is an accordion suitcase that automatically expands whenever you pack more items into it."
Deep Dive: How It Works
#include <vector>: Required header.
Declaration: std::vector<int> scores; (an empty vector of integers) or std::vector<std::string> names = {"Alex", "Ada"};.
.push_back(val): Appends an element to the end of the vector and expands memory automatically.
.size(): Returns the current number of elements.
.pop_back(): Removes the last element.
Range-based for loop: for (int x : vec) { std::cout << x; } gives clean, index-free iteration.
Syntax Blueprint
#include <vector>
std::vector<int> v;
v.push_back(10); // Adds 10
v.push_back(20); // Adds 20
for (int x : v) {
std::cout << x << " ";
}Dynamic resizable vector with push_back and range-based for loop.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using [] on an empty vector: vec[0] = 5;Why it happens: [] modifies an existing index, but cannot add a new slot to an empty vector.
How to fix: Use vec.push_back(5) to add new elements.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Build a numbers vector
Declare std::vector<int> nums;
Push 100 and 200 using push_back().
Print "Vector size: 2".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.