AnyCompiler

Arrays y Vectors

Un array de estilo C tiene un tamaño fijo en tiempo de compilación y ninguna forma integrada de crecer. sizeof(array) / sizeof(array[0]) es el idiom clásico (aunque un poco torpe) para calcular su longitud, ya que un array no rastrea su propio tamaño en tiempo de ejecución.

#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 es la colección creciente principal de C++ — gestiona su propio almacenamiento asignado en el heap y se redimensiona automáticamente a medida que le haces push_back de elementos. Es un template, así que vector<int> y vector<string> son ambas instanciaciones válidas y type-safe.

#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

Siguiente: strings — std::string, un tipo de string real, owned y mutable.

Practice exercise

Dado un vector<int> numbers = {4, 8, 15, 16}, suma todos sus elementos con un range-based for loop e imprime el total.