Catching out_of_range on a vector of vectors
Asked Answered
W

2

21

I have a vector of vectors to establish a map of integers, and I would love to catch a vector out of range error whenever it is thrown, by doing the following:

vector< vector<int> > agrid(sizeX, vector<int>(sizeY));

try {
    agrid[-1][-1] = 5;     //throws an out-of-range
}
catch (const std::out_of_range& e) {
    cout << "Out of Range error.";
}

However, my code doesn't seem to be catching the error at all. It still seems to want to run std::terminate. Does anyone know whats up with this?

Wilford answered 7/10, 2013 at 17:26 Comment(1)
Some IDE like xcode will report an error. Generally you want to use "at"Submediant
D
36

In case you want it to throw an exception, use std::vector::at1 instead of operator[]:

try {
    agrid.at(-1).at(-1) = 5;
}
catch (const std::out_of_range& e) {
    cout << "Out of Range error.";
}

1 - Returns a reference to the element at specified location pos, with bounds checking. If pos is not within the range of the container, an exception of type std::out_of_range is thrown

Demetria answered 7/10, 2013 at 17:29 Comment(0)
A
2

The std::vector::operator [] (size_type) does not apply any range check (which is good). The function std::vector::at(size_type) does (which is good for lazy programmers). Hence ensure a proper range or check first and throw some useful exception (if you actually have to do it).

(Note: In debug compilations it might be different)

Arcadian answered 7/10, 2013 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.