Introducing std::vector
Part of the Logic & Flow section of Coddy's C++ journey — lesson 9 of 56.
You've been working with traditional C-style arrays, which have a fixed size that must be determined when you write your code. But what if you need a collection that can grow or shrink while your program is running? This is where std::vector from the Standard Template Library (STL) becomes invaluable.
A vector is essentially a dynamic array - it can automatically resize itself as you add or remove elements. Unlike regular arrays where you must specify the size upfront, vectors handle memory management for you, expanding when you need more space and contracting when elements are removed.
To use vectors in your program, you need to include the appropriate header at the top of your file:
#include <vector>This flexibility makes vectors perfect for situations where you don't know how many elements you'll need in advance, or when the number of elements changes during program execution. Vectors provide the convenience of automatic memory management while still offering the performance and familiar syntax of arrays.
Cheat sheet
A std::vector is a dynamic array that can automatically resize itself as you add or remove elements, unlike traditional C-style arrays with fixed sizes.
To use vectors, include the header:
#include <vector>Vectors handle memory management automatically, expanding when you need more space and contracting when elements are removed. They're ideal when you don't know how many elements you'll need in advance or when the number of elements changes during program execution.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items