# 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
    

```cpp
#include <vector>

std::vector<int> numbers;
```

Think of a vector as:

> An array with superpowers 🦸

---

## Why Use Vectors Instead of Arrays?

| Feature | Array | Vector |
| --- | --- | --- |
| Size | Fixed | Dynamic |
| Memory Management | Manual | Automatic |
| Bounds Safety | Unsafe | Safer (with `.at()`) |
| Built-in Functions | ❌ | ✅ |
| STL Compatibility | Limited | Full |

---

## Declaring and Initializing Vectors

### Basic Declaration

```cpp
std::vector<int> v;
```

### With Initial Values

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

### With Size and Default Value

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

---

## Adding and Removing Elements

### `push_back()` – Add at End

```cpp
v.push_back(20);
```

### `pop_back()` – Remove Last Element

```cpp
v.pop_back();
```

### `insert()` – Add at Specific Position

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

### `erase()` – Remove Element

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

---

## Accessing Elements

### Using Index

```cpp
cout << v[0];
```

### Using `.at()` (Safer)

```cpp
cout << v.at(0);
```

### First & Last Elements

```cpp
v.front();
v.back();
```

---

## Looping Through a Vector

### Traditional Loop

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

### Range-Based Loop (Recommended)

```cpp
for (int x : v)
    cout << x << " ";
```

### Using Iterators

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

---

## Size vs Capacity (Very Important)

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

Vectors **grow exponentially**, not linearly.

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

👉 Using `reserve()` improves performance in large applications.

---

## Clearing and Resizing

### Clear All Elements

```cpp
v.clear();
```

### Resize Vector

```cpp
v.resize(3);
```

### Check If Empty

```cpp
v.empty();
```

---

## Vector of Vectors (2D Vectors)

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

Access:

```cpp
matrix[0][1] = 5;
```

This is heavily used in:

* Graphs
    
* DP problems
    
* Grids
    

---

## Passing Vectors to Functions

### By Reference (Best Practice)

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

### By Const Reference (Read-only)

```cpp
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

| Operation | Complexity |
| --- | --- |
| Access (`[]`) | O(1) |
| push\_back | Amortized O(1) |
| insert/erase (middle) | O(n) |
| pop\_back | O(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.**
