Arrays and Vectors

A row of boxes

An array stores items side by side in memory, in numbered slots. In C++ you'll mostly use vector: an array that can grow.

Think of it like this: A row of numbered seats in a cinema. To find seat 57 you walk straight to it – you don't check seats 1 to 56 first. That's why v[57] is instant.

OperationC++Big-OWhy
read / change by indexv[i]O(1)jump straight to the slot
add at the endv.push_back(x)O(1)*the next slot is free
remove from the endv.pop_back()O(1)nothing else moves
insert / erase at the frontv.insert(v.begin(), x)O(n)every other item shifts
search for a valuefind(...)O(n)may check every item
sizev.size()O(1)stored

*On average. Sometimes the vector moves to a bigger block of memory, but that's rare.

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

void show(const vector<char>& v) {
    for (char c : v) cout << c << ' ';
    cout << endl;
}

int main() {
    vector<char> seats = {'A', 'B', 'C', 'D'};
    seats.insert(seats.begin(), 'Z');   // A, B, C, D all shift right
    show(seats);
    seats.erase(seats.begin());         // everyone shifts back left
    show(seats);
    seats.push_back('E');               // fast: nothing moves
    show(seats);
    return 0;
}

Output

Z A B C D 
A B C D 
A B C D E 

Walking through a vector

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

int main() {
    vector<int> temps = {31, 29, 35, 33, 28};
    int hottest = 0;
    for (int day = 0; day < (int)temps.size(); day++)
        if (temps[day] > temps[hottest]) hottest = day;
    cout << "Hottest was day " << hottest << " at " << temps[hottest] << endl;
    return 0;
}

Output

Hottest was day 2 at 35

Common mistake: v[i] with an index outside 0 … size − 1 doesn't give an error in C++ – it reads garbage memory or crashes. Always check your loop bounds.

HOME LABS COMMUNITY DASHBOARD