Core Module
12 min forge
C++ STL Vector
Mastering the most versatile dynamic array container in C++.
C++ STL Vector
π What is it
std::vector is a dynamic array container that can resize itself automatically when an element is inserted or deleted. It provides contiguous storage and efficient access.
β‘ When to use
Almost always when you need a list or array. It is the default container of choice in C++ due to its cache friendliness and performance.
π§ Time complexity
- Access: $O(1)$
- Push Back: $O(1)$ amortized.
- Insertion/Deletion (middle): $O(N)$
π» Code example
cpp Standard#include <vector> #include <iostream> std::vector<int> v = {1, 2, 3}; v.push_back(4); // Adds 4 to end std::cout << v.size(); // 4 for (int x : v) std::cout << x << " ";
β Common mistakes
- Not using
v.reserve()when the number of elements is known, leading to multiple reallocations. - Using
v[i]without checking bounds (usev.at(i)for safety). - Erasing elements inside a manual loop without correctly updating the iterator.