Can someone help me to solve this error?
I met a problem when I did an exercise on LeetCode.
The question is finding a number in a [n*m] 2D array.
In an n * m two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.
0 <= n <= 1000
0 <= m <= 1000
For example
/**********input********/
matrix:[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
target:5
/**********output********/
true
And my solution is:
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;
vector<vector<int>>::iterator row;
vector<int>::iterator column;
for(row=matrix.begin();row!=matrix.end();row++){
if(target<*(*row).begin()) return false;
for(column=(*row).begin();column!=(*row).end();column++){
if(target==*column)return true;
else if(target<*column)break;
}
}
return false;
}
};
I got a runtime error when the input is [[ ]]: reference binding to null pointer of type 'int' (stl_iterator.h).
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_iterator.h:797:16
Thanks in advance for your help!
matrix?mandnit's possible to get input with 0 columns, right? In this caseif(target<*(*row).begin())could dereference an past-the-end-iterator. If you know the input for which the code fails please show it.