Vectors and out_of_range exception

Greetings

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.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v(5);
    cout << v[5];

    return 0;
}


Thanks in advance...
Fred.
Nope. vector::at() throws exceptions. vector::operator[] just crashes (if you're lucky).
http://www.cplusplus.com/reference/vector/vector/operator[]/
http://www.cplusplus.com/reference/vector/vector/at/

Hope this helps.
Last edited on
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.

Thanks,
Last edited on
Which book are you reading, if I may ask?
(There are more than a few very bad C++ books.)
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.
That is a good book, but it is dated.
One of the reasons I picked it was because of the recent copyright date (2014)
Why do you say it is dated, I'll know what to watch for.
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

OK I see what you mean.

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.
Last edited on
Topic archived. No new replies allowed.