Aral Code

Functions & Data Lesson 10 of 17

C++ Arrays and Vectors

Store lists in C++ with fixed arrays and resizable std::vector — push_back, size, at, insert, erase, 2D vectors, and passing vectors to functions.

C++ has C-style arrays, but for most purposes you'll use std::vector: a list that grows and shrinks automatically, knows its own size, and can be passed to functions safely.

C-style arrays (quick review)

int grades[5] = {88, 92, 79, 95, 84};
cout << grades[0];        // 88

Their size is fixed, they don't know their own length, and C++ doesn't check the index. That's why vector is preferred.

vector basics

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

int main() {
    vector<int> grades = {88, 92, 79};
    grades.push_back(95);          // add to the end
    grades.push_back(84);

    cout << "Count: " << grades.size() << endl;
    cout << "First: " << grades[0] << ", last: " << grades.back() << endl;

    grades[2] = 81;                // change
    int sum = 0;
    for (int g : grades) sum += g;
    cout << "Average: " << static_cast<double>(sum) / grades.size() << endl;
    return 0;
}

Output

Count: 5
First: 88, last: 84
Average: 88
  • vector<int> means "a vector of ints". Include <vector>.
  • push_back(x) adds to the end; pop_back() removes the last item.
  • size() gives the number of items.
  • v[i] reads item i without checking; v.at(i) checks and throws an error if i is out of range.

Building a vector from input

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

int main() {
    vector<string> names;
    string name;
    cout << "Enter names (type done to finish):" << endl;
    while (cin >> name && name != "done") {
        names.push_back(name);
    }
    cout << "You entered " << names.size() << " names:" << endl;
    for (size_t i = 0; i < names.size(); i++) {
        cout << i + 1 << ". " << names[i] << endl;
    }
    return 0;
}

Output

Enter names (type done to finish):
Ana Ben Carla done
You entered 3 names:
1. Ana
2. Ben
3. Carla

size() returns an unsigned type (size_t), so loop counters compared with it are often declared as size_t to avoid warnings.

Inserting and erasing

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

int main() {
    vector<string> queue = {"Ana", "Ben", "Carla"};
    queue.insert(queue.begin(), "Teacher");      // add at the front
    queue.erase(queue.begin() + 2);              // remove index 2 (Ben)
    for (const string &p : queue) cout << p << " ";
    cout << endl;
    queue.clear();
    cout << boolalpha << queue.empty() << endl;
    return 0;
}

Output

Teacher Ana Carla 
true

begin() is an iterator pointing to the first element; begin() + 2 points to index 2.

Passing vectors to functions

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

double average(const vector<double> &v) {      // read-only, no copy
    double sum = 0;
    for (double x : v) sum += x;
    return v.empty() ? 0 : sum / v.size();
}

void addBonus(vector<double> &v, double bonus) {   // can change
    for (double &x : v) x += bonus;
}

int main() {
    vector<double> scores = {78, 85, 92};
    addBonus(scores, 2);
    cout << "Average after bonus: " << average(scores) << endl;
    return 0;
}

Output

Average after bonus: 87

Unlike C arrays, a vector carries its size with it, so you don't need an extra length parameter.

2D vectors

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

int main() {
    vector<vector<int>> scores = {
        {88, 91, 85},
        {76, 82, 79},
        {95, 93, 97}
    };
    for (size_t r = 0; r < scores.size(); r++) {
        int sum = 0;
        for (int s : scores[r]) sum += s;
        cout << "Student " << r + 1 << ": " << sum / 3.0 << endl;
    }

    vector<vector<char>> board(3, vector<char>(3, '.'));   // 3x3 filled with '.'
    board[1][1] = 'X';
    for (const auto &row : board) {
        for (char c : row) cout << c;
        cout << endl;
    }
    return 0;
}

Output

Student 1: 88
Student 2: 79
Student 3: 95
...
.X.
...

vector vs array

C arrayvector
SizeFixedGrows and shrinks
Knows its lengthNoYes: size()
Bounds checkingNoWith at()
Copy / assignNot directlyYes: v2 = v1;

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which method adds an item to the end of a vector?
2. What's the difference between v[i] and v.at(i)?
3. How should a function receive a vector it only reads?
4. What does vector<int> v(5, 0); create?

By Sir Reyel · Last updated 2026-12-04