Skip to main content

Command Palette

Search for a command to run...

C++ Vectors Explained: The Dynamic Array You’ll Actually Use

Updated
3 min read
C++ Vectors Explained: The Dynamic Array You’ll Actually Use

Introduction

In C++, managing memory manually using arrays can quickly become painful. Fixed sizes, manual resizing, and unsafe operations make traditional arrays error-prone.
This is where std::vector comes in.

A vector is a dynamic array provided by the C++ Standard Template Library (STL) that automatically manages memory, resizes itself, and provides powerful built-in functions.

If you write modern C++ and don’t use vectors—you’re doing it wrong.

What Is a Vector in C++?

A vector is a sequence container that:

  • Stores elements in contiguous memory

  • Can grow or shrink dynamically

  • Allows random access (like arrays)

  • Manages memory automatically

#include <vector>

std::vector<int> numbers;

Think of a vector as:

An array with superpowers 🦸


Why Use Vectors Instead of Arrays?

FeatureArrayVector
SizeFixedDynamic
Memory ManagementManualAutomatic
Bounds SafetyUnsafeSafer (with .at())
Built-in Functions
STL CompatibilityLimitedFull

Declaring and Initializing Vectors

Basic Declaration

std::vector<int> v;

With Initial Values

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

With Size and Default Value

std::vector<int> v(5, 10); // {10, 10, 10, 10, 10}

Adding and Removing Elements

push_back() – Add at End

v.push_back(20);

pop_back() – Remove Last Element

v.pop_back();

insert() – Add at Specific Position

v.insert(v.begin() + 1, 99);

erase() – Remove Element

v.erase(v.begin() + 2);

Accessing Elements

Using Index

cout << v[0];

Using .at() (Safer)

cout << v.at(0);

First & Last Elements

v.front();
v.back();

Looping Through a Vector

Traditional Loop

for (int i = 0; i < v.size(); i++)
    cout << v[i] << " ";
for (int x : v)
    cout << x << " ";

Using Iterators

for (auto it = v.begin(); it != v.end(); it++)
    cout << *it << " ";

Size vs Capacity (Very Important)

v.size();     // Number of elements
v.capacity(); // Allocated memory

Vectors grow exponentially, not linearly.

v.reserve(100); // Pre-allocate memory

👉 Using reserve() improves performance in large applications.


Clearing and Resizing

Clear All Elements

v.clear();

Resize Vector

v.resize(3);

Check If Empty

v.empty();

Vector of Vectors (2D Vectors)

vector<vector<int>> matrix(3, vector<int>(4, 0));

Access:

matrix[0][1] = 5;

This is heavily used in:

  • Graphs

  • DP problems

  • Grids


Passing Vectors to Functions

By Reference (Best Practice)

void print(vector<int>& v) {
    for (int x : v)
        cout << x << " ";
}

By Const Reference (Read-only)

void print(const vector<int>& v);

Common Mistakes to Avoid ❌

  1. ❌ Accessing out-of-bounds indices

  2. ❌ Forgetting #include <vector>

  3. ❌ Passing vectors by value unnecessarily

  4. ❌ Assuming capacity == size


Time Complexity Cheat Sheet

OperationComplexity
Access ([])O(1)
push_backAmortized O(1)
insert/erase (middle)O(n)
pop_backO(1)

When NOT to Use Vector

Avoid vectors when:

  • You need constant-time insertion/deletion in the middle → use list

  • Memory footprint is extremely critical

  • Fixed size is guaranteed → use arrays


Conclusion

std::vector is the backbone of modern C++ programming.
If you master vectors, you unlock:

  • Cleaner code

  • Better performance

  • Safer memory handling

  • STL superpowers

Arrays are history. Vectors are the present or alteast using them in c++ would be right call.

C++ Vectors: Mastering Dynamic Arrays