Lesson 28 of 45
C++Lesson 28: Vector Container
12 min
Course progress62%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 28 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
std::vector is the go‑to dynamic array in C++. It stores elements contiguously, supports random access, and automatically manages its memory.
size(), capacity(), reserve(), shrink_to_fit().operator[], at(), front(), back(), data().push_back(), emplace_back(), pop_back(), clear(), insert(), erase().std::vector<int> histogram(10, 0); // 10 bins initialised to 0
int value;
while (std::cin >> value) {
if (value >= 0 && value < 10) ++histogram[value];
}
for (std::size_t i = 0; i < histogram.size(); ++i) {
std::cout << i << ": " << histogram[i] << '\
';
}
Notice how reserve can prevent reallocations when you know the final size:
std::vector<int> data;
data.reserve(1000); // allocate space for 1000 ints up front
Tip: Prefer
emplace_backwhen constructing an object directly inside the vector to avoid extra moves or copies.
<Alert type="warning">When a vector grows, it may reallocate, invalidating all iterators and references to its elements.