Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching out_of_range on a vector of vectors

Tags:

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?

like image 907
David Chan Avatar asked Oct 07 '13 17:10

David Chan


People also ask

Should I use std for vector?

If you need a "dynamic" array, then std::vector is the natural solution. It should in general be the default container for everything. But if you want a statically sized array created at time of compilation (like a C-style array is) but wrapped in a nice C++ object then std::array might be a better choice.

How do you traverse a vector?

Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() . Where i is the index.

What is STD Out of range?

std::out_of_range It is a standard exception that can be thrown by programs. Some components of the standard library, such as vector , deque , string and bitset also throw exceptions of this type to signal arguments out of range. It is defined as: C++98. C++11.

How do you handle an out of range exception in C++?

To throw an out-of-range exception in C++, you can create an exception object. For this, you can use the out_of_range() constructor. The out_of_range() constructor is defined in the standard C++ library. It takes a string object as its input argument and returns an out-of-range exception.


1 Answers

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

like image 158
LihO Avatar answered Mar 06 '23 07:03

LihO