Skip to main content

Command Palette

Search for a command to run...

vector in c++

Published
4 min readView as Markdown

Complete Guide to vector in C++ — The Most Powerful Dynamic Array

When you start learning modern C++, one of the most important and useful containers you’ll use is std::vector.
It is flexible, dynamic, easy to use, and extremely powerful compared to traditional arrays.

In this blog, we will cover:

  • What is a vector?

  • Why use vector instead of arrays?

  • Most important vector functions

  • How vector grows internally

  • Passing and returning vectors in functions

  • Real working examples + outputs

  • Best practices


🚀 What is a Vector in C++?

A vector is a dynamic array provided by the C++ Standard Template Library (STL).
Unlike arrays, vectors can grow and shrink automatically at runtime.

✔ Key Features

  • Dynamic size (no need to know size at compile time)

  • Continuous memory allocation (fast access)

  • Supports many built-in functions

  • Easy to insert/remove elements

  • Type-safe and flexible


🧬 Basic Syntax

#include <vector>
vector<int> v;       // empty vector
vector<int> v2 = {1,2,3};  // initialized vector
vector<string> names;      // vector of strings

🎯 Why Vector is Better Than Array

FeatureArrayVector
SizeFixedDynamic
MemoryManualAutomatic
FunctionsNoMany inbuilt
SafetyLowHigh
UsabilityHardEasy

🔥 Most Useful Vector Functions

FunctionMeaning
push_back(x)Add element at end
pop_back()Remove last element
size()Number of elements
capacity()Memory allocated
front()First element
back()Last element
clear()Remove all elements
empty()Check vector is empty
insert()Insert at any position
erase()Delete at any position

🧪 Working Example 1 — Basic Vector Operations

Code

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v;

    v.push_back(10);
    v.push_back(20);
    v.push_back(30);

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

    cout << "\nSize: " << v.size();
    cout << "\nCapacity: " << v.capacity();
    cout << "\nFirst element: " << v.front();
    cout << "\nLast element: " << v.back();

    v.pop_back();
    cout << "\nAfter pop_back(), size: " << v.size() << endl;

    return 0;
}

📌 Output

Vector elements: 10 20 30 
Size: 3
Capacity: 4
First element: 10
Last element: 30
After pop_back(), size: 2

⚙️ How Vector Grows Internally

When vector runs out of memory, it doubles its capacity:

Example:

OperationSizeCapacity
Start00
push 111
push 222
push 334
push 444
push 558

This is why vectors are very fast.


🧩 Passing Vector to a Function

1️⃣ Pass by Value (copy created)

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

2️⃣ Pass by Reference (NO COPY — fast)

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

💡 Always prefer passing by reference.


🔁 Returning a Vector from Function

vector<int> getVector() {
    vector<int> v = {1,2,3,4};
    return v;   // safe & efficient
}

🧪 Working Example 2 — Pass and Return Vector

Code

#include <iostream>
#include <vector>
using namespace std;

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

vector<int> createVector() {
    vector<int> v = {100, 200, 300};
    return v;  // RVO optimization - no copy
}

int main() {
    vector<int> nums = {10, 20, 30};

    cout << "Original vector: ";
    printVector(nums);

    vector<int> newVec = createVector();
    cout << "Returned vector: ";
    printVector(newVec);

    return 0;
}

📌 Output

Original vector: 10 20 30 
Returned vector: 100 200 300

🎯 Advanced Operations

🔹 Insert at any position

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

🔹 Erase element

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

🔹 Resize vector

v.resize(10);  // expands and fills with 0

📝 Real Example — Taking Input in Vector

int n;
cin >> n;

vector<int> v(n);

for(int i = 0; i < n; i++) cin >> v[i];

More from this blog

Amit singh's blog

235 posts