Skip to main content

C++ Vectors for Beginners

 If you're new to C++, you've probably met arrays and found them a bit annoying. Their size is fixed, so if you need to store one more item than you planned, you're stuck. Vectors fix that problem.

This guide explains what vectors are and how to use them, one small step at a time. No prior knowledge needed.

What Is a Vector in C++?

A vector is a container that holds a list of items, like numbers or letters. Think of it as a magic shopping list: you can add items, cross them off, and the list stretches or shrinks to fit.

Here's what makes vectors useful:

  • They grow and shrink automatically. You don't have to decide the size in advance.
  • You can jump to any item instantly. Asking for the 3rd item is just as fast as asking for the 300th.
  • Adding or removing at the end is fast.
  • They manage their own memory. You don't have to do it yourself, which is great when you're learning.

Vectors come from the C++ Standard Template Library (STL), a toolbox of ready-made containers and functions that comes with C++.

Your First Vector

To use vectors, add #include <vector> at the top of your program.

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

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

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

    return 0;
}

Output:

10 20 30 40

What's happening here:

  • vector<int> v creates a vector named v that stores whole numbers (int).
  • {10, 20, 30, 40} fills it with starting values.
  • for (int x : v) means "for each item in v, call it x and do something with it." Here we print it.

The Basic Syntax

vector<T> v;
  • T is the type of data you want to store (int, char, double, string, and so on).
  • v is just a name. You can call it anything.

Adding Elements

There are two main ways to add items:

  • push_back(value) adds an item to the end. It's very fast (O(1) on average).
  • insert(position, value) adds an item anywhere you choose. It's slower (O(n)) because the vector has to shift other items over to make room.

What's O(1) and O(n)? This is "Big O" notation, a way to describe how fast something is. O(1) means the time stays about the same no matter how big the vector is. O(n) means the time grows as the vector grows. You don't need to master this yet. Just remember that O(1) is faster.

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

int main() {
    vector<char> v = {'a', 'f', 'd'};

    // Add 'z' at the end
    v.push_back('z');

    // Add 'c' at index 1 (the second spot)
    v.insert(v.begin() + 1, 'c');

    for (char i : v)
        cout << i << " ";
    return 0;
}

Output:

a c f d z

Note that v.begin() + 1 means "the start of the vector, moved over by one spot." Counting in C++ starts at 0, so index 1 is the second position.

Accessing Elements

You can read an item in two ways:

  • v[i] is quick, but it doesn't check whether i is valid.
  • v.at(i) checks first. If the index doesn't exist, it throws an error (std::out_of_range) instead of quietly doing something wrong.

Both take O(1) time. As a beginner, at() is a safer choice while you're learning, because it tells you when you've made a mistake.

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

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

    // Using []
    cout << "Element at index 2 using []: " << v[2] << endl;

    // Using at()
    cout << "Element at index 3 using at(): " << v.at(3) << endl;

    // This would cause an out_of_range error, because
    // there is no index 10 in this vector:
    // cout << v.at(10) << endl;

    return 0;
}

Output:

Element at index 2 using []: 30
Element at index 3 using at(): 40

Updating Elements

To change an item, use its index and the = sign:

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

int main()
{
    vector<int> v = {10, 20, 30};
    cout << "Original value at index 1: " << v[1] << endl;

    // Change the value at index 1
    v[1] = 50;

    cout << "Updated value at index 1: " << v[1] << endl;
    return 0;
}

Output:

Original value at index 1: 20
Updated value at index 1: 50

Finding the Size of a Vector

Use size() to see how many items are inside:

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

int main() {
    vector<char> v = {'a', 'c', 'f', 'd', 'z'};

    cout << v.size();

    return 0;
}

Output:

5

Looping Through a Vector

"Traversing" just means visiting every item, one by one. You have three options:

  1. A regular for loop with an index (v[i])
  2. A range-based for loop (the easiest, and what we've been using)
  3. Iterators (a more advanced tool you can learn later)

Looping through everything takes O(n) time, which makes sense because there are n items to visit.

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

int main() {
    vector<char> v = {'a', 'c', 'f', 'd', 'z'};

    for (char i : v)
        cout << i << " ";
    return 0;
}

Output:

a c f d z

Two handy tips:

  • Use for (char &x : v) when you want to change the items. The & means you're working with the real item, not a copy.
  • Use for (const char &x : v) when you only want to read the items. It avoids making copies, which is more efficient.

Removing Elements

  • pop_back() removes the last item. It's fast (O(1)).
  • erase() removes an item (or a range of items) from anywhere. It's usually O(n), because the items after it have to shift to fill the gap.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<char> v = {'a', 'c', 'f', 'd', 'z'};

    // Remove the last element ('z')
    v.pop_back();

    // Find 'f' and remove it
    v.erase(find(v.begin(), v.end(), 'f'));

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

Output:

a c d

We included <algorithm> here because find() lives there. It searches the vector and tells erase() which item to remove.

Checking If a Vector Is Empty

empty() returns true if there's nothing inside and false if there is:

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

int main() {
    vector<int> v;

    if (v.empty()) {
        cout << "Vector is empty." << endl;
    }

    v.push_back(100);

    if (!v.empty()) {
        cout << "Vector is not empty. First element: " << v[0] << endl;
    }
    return 0;
}

Output:

Vector is empty.
Vector is not empty. First element: 100

It's good practice to check empty() before accessing items, so you don't try to read something that isn't there.

Multidimensional Vectors (Grids and Tables)

Sometimes one row of data isn't enough. A game board, a spreadsheet, or a seating chart all need rows and columns. For that, you can put a vector inside another vector, which is called a 2D vector.

vector<vector<int>> matrix;

Here's an example:

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

int main() {
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // Loop through each row, then each value in that row
    for (const auto &row : matrix) {
        for (const auto &val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

1 2 3
4 5 6
7 8 9

auto tells C++ to work out the type for you, which saves typing when types get long.

Quick Reference Cheat Sheet

What you want to do Function Speed
Add to the end push_back(value) O(1) average
Add anywhere insert(position, value) O(n)
Read an item v[i] or v.at(i) O(1)
Change an item v[i] = newValue O(1)
Get the count size() O(1)
Remove the last item pop_back() O(1)
Remove from anywhere erase() O(n)
Check if empty empty() O(1)

Why Use Vectors?

  • Flexible size: They grow and shrink as your program runs.
  • Fast access: Any item is available instantly by its index.
  • Less hassle: The vector handles memory for you.
  • Works with the STL: You can use it with sorting, searching, and other built-in tools.

Popular posts from this blog

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...