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 (use v.at(i) for safety).
  • Erasing elements inside a manual loop without correctly updating the iterator.