Library contents

C++ std::out_of_range

The checked at member reports an out-of-range position with std::out_of_range.

A simple example

std::out_of_range

  1. Start with A list containing only A
  2. Do this Ask for the third item
  3. Result Outside the list
The only valid item is the first. A bounds check can reject this request before reading.

Syntax

C++ syntax
seats.at(index)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Find a seat after the coach changes

A bus operator replaces a coach with a smaller one. A passenger's saved seat position now falls outside the new seating list, so the booking screen must ask them to choose again.

ResultChoose another seat
lesson.cpp
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>

int main() {
    std::vector<std::string> seats{"Window", "Aisle"};
    try {
        std::cout << seats.at(2) << '\n';
    } catch (const std::out_of_range&) {
        std::cout << "Choose another seat\n";
    }
    return 0;
}
Output
Choose another seat

The saved position is just beyond the two-seat list. The booking desk asks for a replacement seat.

Advertisements

Open the last appointment

A desk offers two appointments and a visitor selects index one. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.

GivenSlots AM, PM · index 1
Worked resultSlot found

Reject a stale bus selection

An old menu points to index two after the coach list shrinks to two stops. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.

GivenStops Hall, Mill · index 2
Worked resultChoose another slot

What to watch for

Using operator[] skips this bounds check in C++17.

Documentation for std::out_of_range