Arrays December 19 ,2025

Vector in C++ STL

A Complete Internal, Theoretical, and Practical Guide

1. What Is a Vector in C++? 

In C++, a vector is a dynamic array provided by the Standard Template Library (STL).
It allows storing elements in contiguous memory locations, just like arrays, but with the added ability to grow and shrink at runtime.

At a conceptual level, a vector solves the biggest limitation of C-style arrays:

fixed size at compile time.

A vector automatically manages memory allocation, resizing, and element shifting while still preserving fast random access.

2. Why Vectors Were Introduced 

C-style arrays:

  • Require fixed size
  • Cannot be resized safely
  • Expose raw memory management
  • Lead to buffer overflows and memory bugs

Vectors were introduced to:

  • Provide dynamic resizing
  • Maintain array-like performance
  • Reduce memory-related errors
  • Support generic programming via templates

Vectors combine:

  • Performance of arrays
  • Flexibility of dynamic memory
  • Safety of standard library abstractions

3. Key Properties of Vector

A vector has three fundamental properties:

  1. Contiguous memory storage
  2. Dynamic resizing
  3. Random access

Because of contiguous storage:

  • v[i] works in constant time
  • Cache locality is preserved
  • Interoperability with C arrays is possible

4. Vector vs Array (Core Difference)

FeatureArrayVector
SizeFixedDynamic
MemoryStack / staticHeap
ResizeNot possibleAutomatic
SafetyNo bounds checkOptional
STL supportNoYes

Vectors internally use dynamic memory allocation, typically via the heap.

5. How Vector Is Stored in Memory 

A vector internally maintains three pointers:

  1. Begin pointer – start of allocated memory
  2. End pointer – end of used elements
  3. Capacity pointer – end of allocated memory

Conceptually:

| element | element | element | free | free | free |
^         ^                   ^
begin     end                 capacity

This structure explains:

  • Difference between size and capacity
  • Why reallocation happens
  • Why push_back is amortized O(1)

6. Size vs Capacity 

Size

  • Number of elements currently stored

Capacity

  • Total number of elements vector can store without reallocating

Code Example

#include 
#include 
using namespace std;

int main() {
    vector v;
    cout << v.size() << endl;
    cout << v.capacity() << endl;
}

Initially:

  • size = 0
  • capacity = implementation dependent (often 0)

7. Vector Growth Strategy (Amortized Analysis)

When a vector becomes full and a new element is inserted:

  1. A new larger block is allocated
  2. Existing elements are copied or moved
  3. Old memory is released

Most implementations:

  • Double the capacity
  • Sometimes increase by factor of 1.5

This is why:

  • push_back() is amortized O(1)
  • Worst case insertion is O(n)

8. Declaring and Initializing Vectors

Basic Declaration

vector v;

With Initial Size

vector v(5);

With Initial Values

vector v(5, 10);

Using Initializer List

vector v = {1, 2, 3, 4};

9. Accessing Elements in Vector

Using Index

v[2]

No bounds checking.

Using at()

v.at(2)
  • Performs bounds checking
  • Throws exception if invalid

Using Front and Back

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

10. Traversing a Vector (All Methods)

Using Index

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

Using Range-Based Loop

for(int x : v)
    cout << x;

Using Iterators

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

Iterators are preferred in STL algorithms.

11. Insertion Operations in Vector

push_back()

Adds element at the end.

v.push_back(10);

Time Complexity:

  • Amortized O(1)
  • Worst case O(n)

insert() at Specific Position

v.insert(v.begin() + 2, 50);

This requires:

  • Shifting elements
  • Possible reallocation

Time Complexity:

  • O(n)

12. Deletion Operations in Vector

pop_back()

v.pop_back();

Time Complexity:

  • O(1)

erase()

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

Time Complexity:

  • O(n)

13. Clearing and Shrinking Vector

clear()

Removes all elements, capacity unchanged.

v.clear();

shrink_to_fit()

Requests capacity reduction.

v.shrink_to_fit();

Note:

  • This is a non-binding request
  • Compiler may ignore it

14. Vector and Memory Reallocation 

#include 
#include 
using namespace std;

int main() {
    vector v;

    for(int i = 0; i < 10; i++) {
        v.push_back(i);
        cout << "Size: " << v.size()
             << " Capacity: " << v.capacity() << endl;
    }
}

This program clearly shows:

  • Capacity growth
  • Reallocation pattern

15. Vector of Objects 

Vectors store objects by value.

vector students;

Each object:

  • Is constructed
  • Copied or moved during reallocation
  • Destroyed when vector is destroyed

This makes understanding copy and move semantics important.

16. Vector and Pointers

You can access underlying array:

int* p = v.data();

Important:

  • Pointer becomes invalid after reallocation
  • Never store raw pointers to vector elements permanently

17. Vector vs Dynamic Array (malloc / new)

FeatureVectormalloc/new
ResizeAutomaticManual
SafetyHighLow
Memory leaksRareCommon
ExceptionsSupportedManual
STL supportFullNone

Vectors should be preferred in almost all cases.

18. Time Complexity Summary

OperationComplexity
AccessO(1)
push_backAmortized O(1)
insertO(n)
eraseO(n)
searchO(n)
resizeO(n)

19. Common Mistakes with Vectors

  1. Assuming capacity equals size
  2. Holding invalidated iterators
  3. Excessive insertions in middle
  4. Forgetting reallocation cost
  5. Using vector when frequent insertions are needed

20. When to Use Vector and When Not To

Use Vector When:

  • Frequent access is required
  • Size grows dynamically
  • Memory safety matters

Avoid Vector When:

  • Frequent insertions in middle
  • Very large data with strict memory constraints
  • Linked behavior is required

Relationship with Other Topics

This topic connects to:

  • Arrays in C
  • Array Operations and Complexity
  • Dynamic Memory Allocation
  • STL Containers
  • Amortized Analysis

After understanding vectors, the next natural comparison is:

Arrays vs ArrayList in Java

 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Array Memo...
Arrays December 12 ,2025

Array Memory Represe...

Array Oper...
Arrays December 12 ,2025

Array Operations and...

Advantages...
Arrays December 12 ,2025

Advantages and Disad...

Arrays in...
Arrays December 12 ,2025

Arrays in C

Arrays vs...
Arrays December 12 ,2025

Arrays vs ArrayList...

JavaScript...
Arrays December 12 ,2025

JavaScript Arrays

Binary Sea...
Arrays December 12 ,2025

Binary Search on Arr...

Two Pointe...
Arrays January 01 ,2026

Two Pointers Techniq...

Prefix Sum...
Arrays January 01 ,2026

Prefix Sum Technique

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com