std::vector in C++
How to use std::vector, the dynamic array of C++, plus size vs capacity, reserve, and iterator invalidation.
std::vector<T> is a resizable array that manages its own memory. It's the default container in C++: fast to iterate, indexable in O(1), and push_back is amortized O(1).
v.size()is how many elements there are;v.capacity()is how many fit before it must grow.- When it grows, it moves everything to a bigger block, which invalidates pointers and iterators into it.
reserve(n)avoids repeated growth when you know the size. v[i]doesn't check bounds;v.at(i)does.- Loop with
for (const auto &x : v).
Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(4);
for (int i = 1; i <= 4; i++) v.push_back(i * i);
int sum = 0;
for (int x : v) sum += x;
std::cout << v.size() << " " << sum << "\n";
return 0;
}
Output:
4 30
Watch it run: How a vector grows