Learn C++
#include "stlcontainers/vector.hpp"

vector in C++

//concept

std::vector<T> is the default container: a dynamically resizing array with contiguous storage, O(1) indexed access, amortized O(1) push_back, and full value semantics (copying a vector copies its elements). For the overwhelming majority of sequential data, vector beats every node-based container on both speed and simplicity.

Growth doubles capacity as needed (so push_back stays amortized constant), reserve() pre-allocates when the final size is known, and shrink_to_fit() can release slack. Iterators and references invalidate on reallocation — index carefully across growth, or reserve first.

//how it works
1

Contiguous and indexed

v[i] reaches any element in O(1); at(i) adds bounds checking that throws instead of corrupting.

2

push_back grows amortized O(1)

Appends usually just write into spare capacity; occasional doubling reallocations average out to constant time.

3

reserve before big fills

v.reserve(10000); allocates once up front — no repeated reallocations, no iterator invalidation mid-fill.

4

Value semantics

Copying, comparing, and assigning vectors works element-wise out of the box — no manual memory code, ever.

//example
#include <iostream>
#include <vector>
 
int main() {
std::vector<int> v;
v.reserve(3);
v.push_back(10);
v.push_back(20);
v.push_back(30);
std::cout << v.size() << ", " << v[1] << std::endl;
return 0;
}
Output
3, 20
1reserve(3) pre-allocates room for three ints, so the pushes never reallocate.
2Three push_backs fill the storage; size() reports 3 elements.
3v[1] indexes the middle element in O(1) — 20 prints alongside the size.
//complexity
time O(1) amortized push_back, O(1) index
space O(n)

Contiguous storage; reallocation on growth invalidates iterators.

//use cases
The default sequential container — reach for it before list or deque
Buffers filled to a known size with reserve() up front
Cache-friendly numeric loops over contiguous doubles or ints
Returning collections from functions by value (moves keep it cheap)

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.