我想解决这个问题问题,
在这样做的时候,看起来就像
for (int i=row1; i<=row2; i++) {
if (col1 != 0) sum -= mat[i][col1-1];
sum += mat[i][col2];
}和
for (int i=row1; i<=row2; i++) {
sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);
}是等价的,但是执行后的结果会导致以下错误
Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34我错过了什么吗?,谢谢。
complete program:
class NumMatrix {
public:
vector<vector<int>> mat;
NumMatrix(vector<vector<int>>& matrix) {
mat = matrix;
for (int i=0; i<matrix.size(); i++) {
for (int j=1; j<matrix[0].size(); j++)
mat[i][j] += mat[i][j-1];
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for (int i=row1; i<=row2; i++) {
if (col1 != 0) sum -= mat[i][col1-1];
sum += mat[i][col2];
// sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0); // this gives error :
// Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h)
// SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
}
return sum;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/发布于 2022-06-03 18:54:54
这句话
sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);等于ti
sum += (mat[i][col2] - (col1 != 0) ) ? mat[i][col1-1] : 0;因此,例如,如果这个表达式(mat[i][col2] - (col1 != 0) )不等于0,那么实际上
sum += mat[i][col1-1];即使col1等于0。
看来你是说
sum += mat[i][col2] - ( (col1 != 0) ? mat[i][col1-1] : 0);注意这个函数
int sumRegion(int row1, int col1, int row2, int col2) {是不安全的不检查row1、row2、col1和col2是否在有效范围内。
https://stackoverflow.com/questions/72493969
复制相似问题