std::out_of_range error

SB26 picture SB26 · Nov 30, 2011 · Viewed 8.9k times · Source

I am working on the following code in opencv in Linux Ubuntu. x_captured and y_captured are "int" type vectors. Size of both vectors is 18.

for (int i=0;i<=x_captured.size();i++)
{
    for (int j=0;j<=y_captured.size();j++)
    {
        if (i!=j)
        {
            if (((x_captured.at(j)-x_captured.at(i))<=2) && 
                ((y_captured.at(j)-y_captured.at(i))<=2))
            {
                consecutive=consecutive+1;
            }
        }
    }
}

But when i=0 and j=18 after that it throws the following error:

terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check

Answer

Marlon picture Marlon · Nov 30, 2011

The problem is that you are using looping from 0 to N when valid indices are 0 to N - 1. This is why you are getting an exception on the last iteration: std::vector::at performs bound checking, if you are out of bounds then an std::out_of_range is thrown.

You need to change your loop's condition to <, not <=.

for (int i = 0; i < x_captured.size(); i++)
{
    for (int j = 0; j < y_captured.size(); j++)
    {
        ...
    }
}