AnyCompiler

Arrays and Vectors

A C-style array has a size fixed at compile time and no built-in way to grow. sizeof(array) / sizeof(array[0]) is the classic (if slightly clunky) idiom for computing its length, since an array doesn't track its own size at runtime.

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    cout << "numbers[2] = " << numbers[2] << endl;
    cout << "size = " << sizeof(numbers) / sizeof(numbers[0]) << endl;
    return 0;
}
Output
numbers[2] = 3
size = 5

std::vector

std::vector is C++'s primary growable collection — it manages its own heap-allocated storage and resizes itself automatically as you push_back elements onto it. It's a template, so vector<int> and vector<string> are both valid, type-safe instantiations.

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

int main() {
    vector<int> numbers = {1, 2, 3};
    numbers.push_back(4);
    numbers.push_back(5);

    for (int n : numbers) {
        cout << n << " ";
    }
    cout << endl;
    cout << "size = " << numbers.size() << endl;
    return 0;
}
Output
1 2 3 4 5 
size = 5

Next: strings — std::string, a real owned, mutable string type.

Practice exercise

Given a vector<int> numbers = {4, 8, 15, 16}, sum all its elements with a range-based for loop and print the total.