Functions and collections · Lesson 9 of 21
std::vector
An array that grows itself: push_back, size versus capacity, and how it's stored.
std::vector is C++'s most important container: an array whose size changes, with elements side by side in memory, so access is very fast. When in doubt, use a vector.
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> names = {"Laila", "Karim"};
names.push_back("Omar");
names.insert(names.begin(), "Nour"); // at the front (slower)
names.pop_back(); // removes "Omar"
for (const std::string& n : names) std::cout << n << " ";
std::cout << "\n" << names.size() << " names, first " << names.front() << "\n";
std::vector<int> zeros(5, 0); // five zeros
zeros[2] = 7;
for (int z : zeros) std::cout << z;
std::cout << "\n";
return 0;
}size and capacity
A vector reserves more room than it needs (capacity). When it fills up, it allocates a bigger block (often double), moves every element, and frees the old one. That's why push_back is fast on average even though it's occasionally slow.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
std::size_t lastCap = v.capacity();
for (int i = 0; i < 20; i++) {
v.push_back(i);
if (v.capacity() != lastCap) {
std::cout << "size " << v.size() << " -> capacity " << v.capacity() << "\n";
lastCap = v.capacity();
}
}
return 0;
}v (capacity 8) =
size = 5; the 3 highlighted slots are reserved but empty. Once they fill, the whole vector moves somewhere bigger.
Spot the bug
This program may crash or print garbage. Which line is the cause?
Exercise
From the vector {4, 9, 2, 7, 5, 8} build a new vector holding only the numbers above 4, and print it.
Expected output: 9 7 5 8
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {4, 9, 2, 7, 5, 8};
std::vector<int> big;
for (int x : big) std::cout << x << " ";
std::cout << "\n";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.