August 8, 2025

std::vector | Vector in C++

Posted on August 8, 2025  •  4 minutes  • 819 words

In C++, std::vector is a dynamic array provided by the Standard Template Library (STL). Unlike traditional arrays with fixed size, a vector can grow or shrink at runtime, making it one of the most widely used containers in modern C++ programming.


YouTube video thumbnail

Key Points:

  • Stores elements contiguously in memory (like arrays).

  • Automatically manages memory allocation.

  • Offers random access to elements in O(1) time.

  • Provides built-in functions for insertion, deletion, and iteration.

Basic Declaration and Initialization

#include <iostream>
#include <vector>

int main() 
{

    // empty vector of integers
    std::vector<int> numbers;

    // vector with 5 elements (default-initialized to 0)
    std::vector<int> nums(5); 

    // vector with 5 elements, each 10
    std::vector<int> values(5, 10);

    // initializer list
    std::vector<int> copy = {1, 2, 3, 4};

    return 0;
}

Adding and Removing Elements

push_back() – Adds an element at the end


vector<int> v;
v.push_back(10);
v.push_back(20);

pop_back() – Removes the last element

v.pop_back();

insert() – Inserts at a specific position

// insert 15 at index 1
v.insert(v.begin() + 1, 15);

erase() – Removes elements from a specific position or range


// remove first element
v.erase(v.begin()); 

// remove first 2 elements
v.erase(v.begin(), v.begin() + 2);

clear() – Removes all elements

v.clear();

Accessing Elements

vector<int> v = {10, 20, 30};

// direct access (no bounds checking)
cout << v[0] << endl;

// safe access (throws exception if out of range)
cout << v.at(1) << endl;

// first element
cout << v.front() << endl;

// last element
cout << v.back() << endl;  

Iterating Over a Vector

Using a for loop

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

Using a range-based for loop

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

Using iterators

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

Capacity Functions

vector<int> v = {1, 2, 3};
cout << "Size: " << v.size() << endl;
cout << "Capacity: " << v.capacity() << endl;

// preallocate space
v.reserve(10);
cout << "New capacity: " << v.capacity() << endl;

// reduce capacity to match size
v.shrink_to_fit(); 

Resizing a Vector


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

// adds 2 elements with default value 0
v.resize(5);

// removes last 3 elements
v.resize(2); 

Vector of Custom Objects

struct Person 
{
    string name;
    int age;
};

vector<Person> people = {{"ANOOP", 25}, {"VINEETH", 22}};
people.push_back({"SIDHARTH", 23});

Performance Tips

  • Use reserve() when you know the expected size to avoid repeated reallocations.
  • Access with [] for speed, but use .at() when you need bounds checking.
  • Prefer emplace_back() over push_back() when creating objects.
struct Point 
{
    Point(int a, int b) : x(a), y(b) {}
    int x, y;
};

vector<Point> points;

// constructs directly in place
points.emplace_back(1, 2);

std::vector is one of the most powerful and versatile containers in C++. It offers the convenience of dynamic sizing, safety with .at(), and high performance with contiguous memory storage. If you’re starting with STL, mastering std::vector is the perfect first step.

Complete Example

#include <iostream>
#include <vector>

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

    for (int i = 1; i <= 5; i++)
        nums.push_back(i * 10);

    std::cout << "Numbers: ";
    for (int n : nums)
        std::cout << n << " ";
    std::cout << std::endl;

    nums.insert(nums.begin() + 2, 25);
    nums.erase(nums.begin());

    std::cout << "After modifications: ";
    for (int n : nums)
        std::cout << n << " ";
    std::cout << std::endl;

    return 0;
}

std::vector Cheat Sheet – C++

Category Function / Syntax Description
Syntax std::vector<T> v; Empty vector
std::vector<T> v(size); Vector with size elements
std::vector<T> v(size, value); Vector with elements initialized to value
std::vector<T> v = {val1, val2}; Initialize with list
Add / Remove v.push_back(value); Add element at end
v.pop_back(); Remove last element
v.insert(iter, value); Insert element at position
v.erase(iter); Remove element at position
v.erase(start, end); Remove range of elements
v.clear(); Remove all elements
Access v[index] Direct access (no bounds check)
v.at(index) Safe access (bounds check)
v.front() First element
v.back() Last element
Capacity v.size() Number of elements
v.capacity() Allocated storage
v.empty() Check if vector is empty
v.reserve(n) Preallocate storage
v.shrink_to_fit() Reduce capacity to size
v.resize(count) Change number of elements
Iteration for (size_t i = 0; i < v.size(); i++) Loop by index
for (auto x : v) Range-based loop
for (auto it = v.begin(); it != v.end(); ++it) Iterator loop
Performance Tips Use reserve() Avoids multiple allocations
Use emplace_back() Constructs in place
Prefer [] over .at() Faster (no bounds check)
Avoid middle insertions Consider std::list/std::deque
Follow me

I work on everything coding and share developer memes