The book I am reading gives me the impression that because vectors keep track of their own size, the subscript operation ([]) will throw an exception if you try to access an element that is out of said vector's range. The code below does not back that up, it just prints a garbage number when it reads an out_of_range element. I guess I am getting the wrong impression from the book. Please confirm.
A quote from the vector::at page seems to spell it out clearly
The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater or equal than its size). This is in contrast with member operator[], that does not check against bounds.
which supports my experience with my sample code, and also implies that my impression from the book was an incorrect one.
Stroustrop's Beginner's book Programming Principles and Practice using C++.
Not really my type of book. If I could make the choice again, I'd pick something else. But I've paid for it and I have to try and get my money's worth.
I guess I am getting the wrong impression from the book.
The problem is that you're not using the header supplied with the book, "std_lib_facilities.h". That header "modifies" the std::vector to do minimal range checking much like using the at() function. If you use that header instead an exception will be thrown if you access the vector out of range.
But using the actual std::vector the operator[] doesn't throw exceptions for out of bounds access, unlike the at() member function. This fact is explained in chapter 19.4
I can't say I agree with the use of Stroustrup's header. After all, a few #includes and some basic error handling is hardly the most difficult thing to understand about standard c++. Better to stick with the standard.