01 / 21

std::vector
Dynamic Arrays in C++

Master the most essential container in the C++ Standard Library: std::vector. Learn to create, modify, and iterate over dynamic arrays with confidence.

C++

What Is std::vector?

A std::vector is a sequence container from the C++ Standard Library that stores elements in contiguous memory, just like a plain array, but can grow and shrink at runtime. You never need to declare a fixed size up front.

How Memory Works Inside

capacity = 8 size = 5 10 [0] 20 [1] 30 [2] 40 [3] 50 [4] ? ? ? size() Number of elements currently stored capacity() Total allocated slots before reallocation

Why Use std::vector?

Dynamic Size
No need to know the number of elements at compile time. Add or remove on the fly.
Cache Friendly
Contiguous memory layout means fast iteration: great for CPU cache performance.
Safe Access
Use .at(i) for bounds-checked access that throws on out-of-range indices.

Core Declaration Syntax

#include <vector>

// Empty vector of ints
std::vector<int> nums;

// Initialize with values
std::vector<int> scores = {90, 85, 92, 78};

// 5 elements, all initialized to 0
std::vector<int> zeros(5, 0);

// Vector of strings
std::vector<std::string> names = {"Alice", "Bob"};

Essential Operations

std::vector push_back(val) pop_back() size() operator[i] at(i) clear() empty() begin() / end() Modify / Iterate Access Query Remove

std::vector vs Plain Array

std::vector int arr[N]
Size Dynamic: grows at runtime Fixed at compile time
Memory Heap (automatic) Stack (usually)
Bounds Check .at(i) throws exception None: undefined behavior
Knows Its Size .size() always available Must track separately
Copy Simple: v2 = v1; Manual loop or memcpy
Performance Same contiguous access Same contiguous access

Step-by-Step Usage Pattern

1
Include the header: add #include <vector> at the top of your file.
2
Declare: choose the element type, e.g. std::vector<int> v;
3
Populate: use push_back() to add elements, or initializer-list syntax {1, 2, 3}.
4
Access: use v[i] for fast access or v.at(i) for safe access.
5
Iterate: use a range-based for loop: for (auto& x : v).

Example 1: Building a Vector

#include <vector>
#include <iostream>

int main() {
    std::vector<int> grades;

    grades.push_back(88);
    grades.push_back(95);
    grades.push_back(72);
    grades.push_back(91);

    // Print all grades
    for (int g : grades) {
        std::cout << g << " ";
    }
    // Output: 88 95 72 91
}

Example 2: Access and Modify

std::vector<int> v = {10, 20, 30, 40, 50};

// Read element at index 2
int x = v[2];       // x = 30

// Modify element at index 0
v[0] = 99;          // v is now {99, 20, 30, 40, 50}

// Safe access with bounds checking
int y = v.at(4);    // y = 50

// This would throw std::out_of_range:
// int z = v.at(10);

// Get first and last elements
int first = v.front(); // 99
int last  = v.back();  // 50

Example 3: Algorithms with Vectors

#include <vector>
#include <algorithm>
#include <numeric>

std::vector<int> v = {5, 2, 8, 1, 9, 3};

// Sort ascending
std::sort(v.begin(), v.end());
// v = {1, 2, 3, 5, 8, 9}

// Find an element
auto it = std::find(v.begin(), v.end(), 8);

// Sum all elements
int total = std::accumulate(v.begin(), v.end(), 0);
// total = 28

Three Ways to Iterate

Range-Based For
for (auto& x : v) {
  cout << x;
}
Index-Based
for (size_t i = 0;
  i < v.size(); i++) {
  cout << v[i];
}
Iterator-Based
for (auto it = v.begin();
  it != v.end(); ++it) {
  cout << *it;
}

Time Complexity of Operations

Operation Complexity Notes
push_back() Amortized \( O(1) \) Occasional reallocation
pop_back() \( O(1) \) No reallocation
operator[] / at() \( O(1) \) Direct pointer arithmetic
insert(pos, val) \( O(n) \) Shifts elements right
erase(pos) \( O(n) \) Shifts elements left
size() / empty() \( O(1) \) Stored internally

The Erase-Remove Idiom

Removing elements by value is a two-step process in C++. std::remove shifts unwanted elements to the end, and erase actually shrinks the vector.

std::vector<int> v = {1, 3, 2, 3, 5, 3, 7};

// Remove all 3s
v.erase(
    std::remove(v.begin(), v.end(), 3),
    v.end()
);
// v = {1, 2, 5, 7}

Common Mistakes

✕ Out-of-Bounds Access
Using v[i] where i >= v.size(). This is undefined behavior: no exception, just a silent bug. Use .at(i) to catch it.
✕ Forgetting to Include
Writing std::vector without #include <vector>. Some compilers include it implicitly, masking the error until you switch compilers.
✕ Modifying During Iteration
Calling push_back() or erase() inside a range-based for loop invalidates iterators and causes crashes.

Quick Reference Cheat Sheet

Method What It Does Returns
push_back(val) Adds val to end void
pop_back() Removes last element void
size() Current element count size_t
empty() Checks if size is 0 bool
at(i) Bounds-checked access T&
front() / back() First / last element T&
clear() Removes all elements void
reserve(n) Pre-allocates capacity void

Question 1 of 5

What is the time complexity of accessing an element with v[i] in a std::vector?

Question 2 of 5

What happens when you call v.at(10) on a vector with only 5 elements?

Question 3 of 5

After this code runs, what does v contain?

std::vector<int> v = {1, 2, 3};
v.push_back(4);
v.pop_back();
v.pop_back();

Question 4 of 5

Which loop syntax is the most idiomatic modern C++ way to iterate over a vector?

Question 5 of 5

Why is inserting an element in the middle of a std::vector \( O(n) \)?