Index Out of Range

What happens when you ask for an index where there is no element? For example, index 3 in a vector of three elements:

std::vector<int> numbers = {10, 20, 30};
std::cout << numbers[3] << std::endl;

The program prints some meaningless number, such as:

44225

Square brackets don't check whether the index belongs to the vector. The program simply reads whatever lies in memory after the end of the vector, much like when you print a variable that you didn't give a starting value. The next run may print a different number, and when the index is far past the end, the program may even crash. Nothing warns you about the mistake, which makes it hard to find. Negative indexes, which you may know from other languages, don't work in C++ either: numbers[-1] is outside the vector too.

The method at() is safer. numbers.at(1) does the same as numbers[1], but checks the index first. When the index is outside the vector, the program stops with an error:

std::vector<int> numbers = {10, 20, 30};
std::cout << numbers.at(1) << std::endl;
std::cout << numbers.at(3) << std::endl;
std::cout << "End" << std::endl;

The program prints 20 and stops. The text End is never printed. Instead, the output shows a red error message that contains out_of_range. You know right away that an index is wrong, and the last line printed shows you where the program stopped.

You can also change an element with at(), just like with square brackets: numbers.at(0) = 15;

Square brackets are shorter, and you'll see them more often in programs. When you're not sure an index is right, use at(). But the best protection is to get your indexes right: the first element has index 0, and the last one size() - 1.

Instructions

The program should print the temperature on Monday, the first day of the week, and on Sunday, the last day. Run it: both temperatures are wrong. First, fix the index for Monday, so that the output includes the line Monday: 18.

For Sunday, replace temperatures[7] with temperatures.at(7) and run the program. It stops with an error, because index 7 is outside the vector. Then fix the index in at(): Sunday is the last element, so its index is temperatures.size() - 1. The program then prints Sunday: 20.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

5/10