Topic 54 of 91 9. C++ Standard Template Library (STL) Interactive Tutorial

std::vector in C++: Dynamic Arrays, Capacity, and Common Operations

8 mins read Last updated: 26 Sep 2026 15,398 views

Direct Answer & Core Concept

std::vector is a dynamic contiguous array that grows automatically when elements are added. size() is the number of elements currently stored, whereas capacity() is the total memory allocated before a reallocation is triggered. When capacity is exceeded, vector allocates a larger chunk (typically 1.5x or 2x) and moves elements.

Detailed Explanation & Mechanics

1. Internal Structure (3 Pointers):

Architecture Diagram
std::vector memory management:
┌──────────────┬───────────────────────────────┬────────────────────────┐
│ [0] [1] [2]  │ (Unused Allocated Storage)    │                        │
└──────────────┴───────────────────────────────┴────────────────────────┘
▲              ▲                               ▲
begin()        size() / end()                  capacity()

2. Key Operations:

  • push_back(v) / emplace_back(args...): Amortized $O(1)$ append.
  • reserve(n): Allocates capacity in advance without creating elements.
  • shrink_to_fit(): Frees unused extra capacity.

Runnable Code Example: std::vector in C++: Dynamic Arrays, Capa

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;
    vec.reserve(5); // Pre-allocate memory for 5 elements

    std::cout << "Initial: Size = " << vec.size() << ", Capacity = " << vec.capacity() << "\n";

    for (int i = 1; i <= 6; ++i) {
        vec.push_back(i * 10);
        std::cout << "Added " << i * 10 << " -> Size: " << vec.size() 
                  << ", Capacity: " << vec.capacity() << "\n";
    }

    std::cout << "Elements: ";
    for (int val : vec) std::cout << val << " ";
    std::cout << "\n";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is iterator invalidation in `std::vector`?

A: When a vector reallocates memory due to exceeding its capacity during push_back or insert, all existing pointers, references, and iterators to its elements become dangling and invalid.
Q

Q: What is the benefit of `emplace_back` over `push_back`?

A: `emplace_back` constructs the object in-place directly in the vector's allocated storage using forwarded constructor arguments, avoiding temporary object construction and copy/move operations.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

• Call reserve() whenever the approximate number of items is known to eliminate multiple reallocations.
• Use emplace_back() instead of push_back() for non-primitive objects.
• Use .at(index) when bounds-checking is required, or operator[] for maximum speed in verified loops.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.