Std :: out_of_range error

I am working on the following code in opencv on Linux Ubuntu. x_captured and y_captured are vectors of type "int". The 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 produces the following error:

ending a call after calling an instance of 'std :: out_of_range' what (): vector :: _ M_range_check

+4
source share
2 answers
 for (int i=0;i<=x_captured.size();i++) { for (int j=0;j<=y_captured.size();j++) 

You must change <= to < and try again.

enter image description here

An example of an array called Billy: Size: 5, but the last index is 4. Get it? :)

+4
source

The problem is that you use a loop from 0 to N when the valid indices are from 0 to N - 1. That's why you get an exception at the last iteration: std::vector::at performs a binding check if you don't use borders, and then std::out_of_range .

You need to change the loop condition to < , not <= .

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

Source: https://habr.com/ru/post/1383964/


All Articles