Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::out_of_range error

Tags:

c++

std

opencv

out

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

like image 504
SB26 Avatar asked Jan 18 '23 04:01

SB26


2 Answers

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++)
    {
        ...
    }
}
like image 125
Marlon Avatar answered Jan 22 '23 09:01

Marlon


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

You should change the <= to < and try again.

enter image description here

Example array named Billy : Size : 5 but last index is 4. Get it? :)

like image 39
FailedDev Avatar answered Jan 22 '23 11:01

FailedDev