⚙️ C++ Intermediate

What is std::vector and how does it work internally?

Why Interviewers Ask This

This tests whether you can apply C++ knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

std::vector is the most used STL container — a dynamic array that grows automatically. Understanding its internals explains its performance characteristics. Internal structure: three pointers: begin (pointer to first element), end (pointer past last element), capacity_end (pointer to end of allocated memory). All elements stored in a contiguous block of heap memory. Size vs capacity: std::vector<int> v; v.reserve(100); // Allocate for 100 without adding elements std::cout << v.size(); // 0 -- no elements std::cout << v.capacity(); // 100+ -- allocated space. Growth strategy (amortized O(1) push_back): when capacity is exceeded, vector allocates a new block (typically 1.5x or 2x larger), copies/moves all elements, frees old block. Example: capacity 1 → 2 → 4 → 8 → 16... Total copy operations for n pushes: O(n) amortized → O(1) per push. Key operations and complexity: v.push_back(x); // O(1) amortized v.pop_back(); // O(1) v[i]; // O(1) -- random access v.insert(it, x); // O(n) -- shifts elements v.erase(it); // O(n) -- shifts elements v.clear(); // O(n) -- destroys elements v.size(); // O(1) v.empty(); // O(1) v.begin()/end(); // O(1). Reserve to avoid reallocations: v.reserve(1000); // Single allocation for (int i = 0; i < 1000; ++i) v.push_back(i); // No reallocations!. Shrink to fit: v.shrink_to_fit() — release excess capacity. emplace_back vs push_back: emplace_back constructs in-place (no temporary): v.emplace_back(42); // Constructs directly v.push_back(MyClass(42)); // Constructs temporary then moves. Memory layout: contiguous memory enables cache-friendly iteration and pointer arithmetic — vector is often faster than list even for insert/delete due to cache effects.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.