2010-10-07 61 views
0

我已经看到了这个代码查找矩阵的次要:C++中的奇怪表达式 - 这是什么意思?

RegMatrix RegMatrix::Minor(const int row, const int col)const{ 
    //printf("minor(row=%i, col=%i), rows=%i, cols=%i\n", row, col, rows, cols); 
assert((row >= 0) && (row < numRow) && (col >= 0) && (col < numCol)); 

RegMatrix result(numRow-1,numCol-1); 

// copy the content of the matrix to the minor, except the selected 
    for (int r = 0; r < (numRow - (row >= numRow)); r++){ 
    for (int c = 0; c < (numCol - (col > numCol)); c++){ 
    //printf("r=%i, c=%i, value=%f, rr=%i, cc=%i \n", r, c, p[r-1][c-1], r - (r > row), c - (c > col)); 
    result.setElement(r - (r > row), c - (c > col),_matrix[r-1][c-1]); 
    } 
} 
    return result; 
} 

这是第一次遇到一个代码行像这样表示:R <(numRow行 - (行> = numRow行))。

这是什么意思?

回答

2

(row >= numRow)是一个布尔表达式。如果operator>=尚未超载,则其应评估为true,如果row大于或等于numRow,则以其他方式评估为false。将此布尔值转换为减法整数时,它将变为1,否则为0。

+0

哦,我现在得到这个。 – limlim 2010-10-07 08:54:24

+0

那么,在将值复制到矩阵中时,此代码如何“忽略”给定的行和列号?它仍然是一个神秘的代码给我... – limlim 2010-10-07 08:55:37

1

(row >= numRow)是一个布尔表达式,这样使用时被转换为int,与true成为1false成为0

1

一个更为清楚的表达方式可能是:

r < (row >= numRow ? numRow - 1 : numRow)

0

row >= numRow会返回一个true或false,这是隐式转换成整数01。所以,做什么基本上是一样的:

r < (numRow - (row >= numRow ? 1 : 0)) 
0

row >= numRow将返回1,如果row大于或等于numRow行,否则为0

因此,行代码就相当于这样的功能:

bool foo() { 
    if(row >= numRow) 
     return r < numRow - 1; 
    else 
     return r < numRow; 
} 
0

使用比较运算符的结果是任一的false一个true,其使用时为一个整数是10

r < (numRow - (row >= numRow))

是相同

​​3210如果(row >= numRow)

否则为r < numRow

0

正如其他人之前说的,它只是一个bool表达式之前铸成int减少(这意味着:如果row >= numRow为减1)。

但我会补充说这是非常荒谬的。你已经声称row < numRow,所以row >= numRow将违反你的功能的先决条件。 col > numCol在下面一行中也是如此。