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?
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.
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.
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.
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.
In case you want it to throw an exception, use std::vector::at
1 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With