Line 1033: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Meu código é o seguinte:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
int i = 0;
int j = matrix[0].size()-1;
while(i<matrix.size() && j>=0)
{
if(target < matrix[i][j])
{
j--;
}
else if(target > matrix[i][j])
{
i++;
}
else{
return true;
}
}
return false;
}
};
Este erro ocorre porque a matriz de vetores está fora dos limites e o contêiner de vetores não pode usar o método de acesso subscrito antes que o espaço de memória seja alocado!
Neste caso de teste, um vetor vazio é inserido, então um erro de array fora dos limites ocorre em matrix[0].
Basta adicionar um julgamento vazio antes disso, a função de julgamento vazio de vector é
o código modificado de empty():
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.empty())
{
return false;
}
int i = 0;
int j = matrix[0].size()-1;
while(i<matrix.size() && j>=0)
{
if(target < matrix[i][j])
{
j--;
}
else if(target > matrix[i][j])
{
i++;
}
else{
return true;
}
}
return false;
}
};