C++ Foundations

Lesson 5 of 6

Arrays and Vectors

Most programs need to work with collections of values, not just single variables. C++ gives you two main options: fixed-size arrays and resizable vectors.

#include <iostream>
#include <vector>

int main() {
    int scores[3] = {80, 92, 67};   // fixed-size array
    std::cout << "first score: " << scores[0] << std::endl;

    std::vector<int> xp = {10, 20, 30};   // resizable array
    xp.push_back(40);

    int total = 0;
    for (int value : xp) {
        total += value;
    }
    std::cout << "total xp: " << total << std::endl;
    std::cout << "vector size: " << xp.size() << std::endl;

    return 0;
}

Arrays vs. vectors

  • A plain array (int scores[3]) has a fixed size decided at compile time, it can never grow or shrink, and accessing an out-of-bounds index (like scores[5]) is undefined behavior, C++ won't stop you.
  • std::vector<T>, part of the Standard Template Library (STL), is a resizable array, push_back adds an element, size() tells you how many there are.
  • The range-based for (int value : xp) loop visits every element without needing an index, read it as "for each value in xp".

TIP

When you're not sure how many elements you'll need, reach for std::vector by default, plain arrays are mostly useful when the size is small and fixed ahead of time.

📝 Arrays & Vectors Quiz

Passing score: 70%
  1. 1.What is the main advantage of std::vector over a plain fixed-size array?

  2. 2.The method used to add an element to the end of a vector is ____().

  3. 3.An array declared as `int scores[3]` can change size after it is created.