Vectors & Sequence Containers
Prerequisites: The STL: an overview
std::vector is a dynamically-growable array — the everyday
default sequence container, playing the same role Java's
ArrayList does.
#include <vector>
std::vector<int> numbers = {1, 2, 3};
numbers.push_back(4);
std::cout << numbers[0] << std::endl; // 1
std::cout << numbers.size() << std::endl; // 4
for (int n : numbers) {
std::cout << n << " ";
}
Other sequence containers exist for specific needs:
std::array<T, N> (a fixed-size array with bounds-checked
.at()), std::deque (efficient push/pop at both ends), and
std::list (a doubly-linked list) — but vector should be the
default choice unless a specific need points elsewhere.
Common mistakes
- Using
[]when out-of-bounds safety matters — like a C array,[]on avectordoes no bounds checking. Use.at(index)instead, which throwsstd::out_of_rangeon an invalid index.
Practice
Create a std::vector<int>, add the numbers 1 through 5, and print
their sum using a range-based for loop.
Show solution
std::vector<int> nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int n : nums) {
sum += n;
}
std::cout << sum << std::endl; // 15