Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top