2010-10-07 101 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在下面一行中也是如此。