C++ · Beginner level

Beginner level · Module 3: Vectors, Arrays and Strings · Lesson 1 of 3

std::vector and std::array

Store many values in vectors that grow and fixed-size arrays, and loop over them safely.

In this lesson you will

  • Create, fill and loop over vectors and arrays
  • Explain why out-of-range access is dangerous and how at() helps

Key concepts

std::vectorpush_back and size()std::arrayundefined behaviour

The lesson

std::vector<int> fares; holds a list that grows with fares.push_back(500). size() gives the number of elements, and indexes run from 0 to size() - 1. std::array<int, 7> holds exactly seven values, fixed at compile time.

Reading past the end with fares[10] is undefined behaviour: the program may print rubbish, crash or appear to work. fares.at(10) checks the index and throws std::out_of_range, which is safer while learning and debugging.

Range-based for loops visit every element: for (int f : fares). Use for (int& f : fares) to change elements in place and for (const auto& name : names) to read large elements without copying.

Step by step

  1. Create a vector of fares and add values with push_back.
  2. Print them with a range-based for loop.
  3. Access an index past the end with at() and observe the exception.
  4. Double every fare in place using a reference in the loop.

Practice activity

Store a week's daily sales in a std::array<int, 7> and print the total and the best day.

Expected result: The program prints the correct total and names the day with the highest sales.

Check your understanding

  1. What is undefined behaviour?

    Show answer

    Behaviour the language does not define, such as reading past the end of a vector; anything can happen.

  2. How do you change elements inside a range-based for loop?

    Show answer

    Use a reference: for (int& x : v).

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.