Skip to content

Module 8 · The Standard Template Library — topic 2 of 7

Vectors in Depth

std::vector internals: size vs capacity, growth and reallocation, emplace_back, erase-remove, sorting and searching, and iterator invalidation.

Beginner 14 min read·Lesson 32 of 40 in C++ Programming

Learning objectives

  • Explain size, capacity and reallocation
  • Insert and erase elements efficiently
  • Avoid iterator invalidation bugs

Definition

std::vector<T> is a sequence container storing elements contiguously in a dynamically allocated array that grows geometrically, providing O(1) random access and amortised O(1) insertion at the end.

Introduction

A vector keeps a block of memory larger than it needs. When the block fills, it allocates a bigger one (typically 1.5× or 2×), moves the elements and frees the old block. That is why push_back is fast on average but can occasionally invalidate pointers to elements.

Because elements are contiguous, a vector can be passed to C functions expecting a pointer and length, and iterating it is extremely cache-friendly. These two properties explain why experienced C++ programmers reach for vector first and only switch containers after measuring.

Why it matters

Vector is the most used container; knowing its costs makes programs fast.

Erasing while iterating is a common source of crashes.

Detailed explanation

size() is the number of elements; capacity() is how many fit before reallocation. reserve(n) pre-allocates; shrink_to_fit() requests releasing unused capacity.

emplace_back(args...) constructs the element in place instead of constructing then copying/moving.

Inserting or erasing in the middle shifts later elements: O(n).

Erase-remove idiom: v.erase(std::remove_if(v.begin(), v.end(), pred), v.end()); removes all matching elements in one pass. C++20: std::erase_if(v, pred).

Reallocation invalidates all iterators, pointers and references; erasing invalidates those at or after the erase point.

Syntax

C++
std::vector<Student> v;
v.reserve(100);
v.emplace_back(101, "Asha"); // constructs in place
v.erase(v.begin() + 2); // remove third element
v.erase(std::remove_if(v.begin(), v.end(), failed), v.end());
std::sort(v.begin(), v.end(), by_marks);
  • Reserve when the final size is known.
  • clear() sets size to 0 but usually keeps capacity.
  • data() gives a pointer to the contiguous storage.

Code examples

Size and capacity

C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(10);
for (int i = 0; i < 6; ++i) v.push_back(i);
std::cout << v.size() << ' ' << (v.capacity() >= 10) << '\n';
v.clear();
std::cout << v.size() << ' ' << v.empty() << '\n';
return 0;
}
Output
6 1
0 1

emplace_back

C++
#include <iostream>
#include <string>
#include <vector>
struct Item {
Item(std::string n, int q) : name(std::move(n)), qty(q) {}
std::string name;
int qty;
};
int main() {
std::vector<Item> cart;
cart.emplace_back("pen", 3);
cart.emplace_back("book", 1);
for (const auto& i : cart) std::cout << i.name << 'x' << i.qty << ' ';
std::cout << '\n';
return 0;
}
Output
penx3 bookx1

More examples

Erase-remove, sort and binary search

C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> marks{55, 32, 91, 38, 77, 64, 12};
marks.erase(std::remove_if(marks.begin(), marks.end(), [](int m) { return m < 40; }), marks.end());
std::sort(marks.begin(), marks.end());
for (int m : marks) std::cout << m << ' ';
std::cout << '\n';
std::cout << std::binary_search(marks.begin(), marks.end(), 77) << ' ';
auto it = std::lower_bound(marks.begin(), marks.end(), 70); // first >= 70
std::cout << *it << " at index " << (it - marks.begin()) << '\n';
return 0;
}
Output
55 64 77 91 
1 77 at index 2

Step-by-step explanation

  • remove_if moves the kept elements forward and returns the new logical end.
  • erase then deletes the leftover tail in one call.
  • Binary search requires sorted data.
  • lower_bound returns the first element not less than 70.

Expected output

Running “Erase-remove, sort and binary search” prints exactly:

TextOutput
55 64 77 91
1 77 at index 2

Practical applications

  • Particle systems store particles in vectors and erase dead ones each frame.
  • Leaderboards are sorted vectors.
  • Buffers passed to C APIs use v.data().

Best practices

  • Use reserve for known sizes.
  • Use erase-remove (or std::erase_if) to delete by condition.
  • Re-acquire iterators after modifying the vector.

Common mistakes

Erasing inside a range-for

Avoid

for (auto it = v.begin(); it != v.end(); ++it) if (*it < 0) v.erase(it);

Prefer

v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x < 0; }), v.end());

erase invalidates it; incrementing it afterwards is undefined behaviour.

Keeping a pointer across push_back

Avoid

int* first = &v[0];
v.push_back(9);
*first = 1;

Prefer

v.push_back(9);
v[0] = 1;

If push_back reallocates, first dangles.

Important notes

  • Growth factor is implementation-defined (libstdc++ doubles, MSVC grows by 1.5×).
  • std::vector<bool> stores bits, so &v[0] is not a bool*.

Key takeaways

  • capacity ≥ size; reallocation invalidates everything.
  • emplace_back constructs in place.
  • Erase-remove deletes by condition efficiently.

Try it yourself

  1. 1
    Remove duplicates from a vector using sort + unique + erase.
  2. 2
    Print capacity after each push_back for 20 pushes and describe the growth pattern on your compiler.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the difference between size() and capacity() of a vector?
  • BeginnerWhat does `emplace_back` do differently from `push_back`?
  • ModerateWhat is printed?
Practise this topic