2016-02-27 81 views
-4

有人可以解释这行代码何时结束吗? :解释这行代码

void constituteSubsequence(int i){ 
    if(Pred[i] + 1) constituteSubsequence(Pred[i]); 
    cout << a[i] << " "; 
} 

在这个程序计算最长递增子:

#include <iostream> 
using namespace std; 
int Pred[1000]; //Pred is previous. 
int a[1000], v[1000], n, imax; 
void read() { 
    cout << " n = "; 
    cin >> n; 
    cout << " Sequence: "; 
    for (int i = 0; i < n; i++) { 
     cin >> a[i]; 
    } 
} 
void constituteSubsequence(int i) { 
    if (Pred[i] + 1) constituteSubsequence(Pred[i]); 
    cout << a[i] << " "; 
} 
void calculate() { 
    int i, j; 
    v[0] = 1; 
    imax = 0; 
    Pred[0] = -1; 
    for (int i = 1; i < n; i++) { 
     v[i] = 1; 
     Pred[i] = -1; 
     for (int j = 0; j < i; j++) { 
      if (a[j] < a[i] && v[j] + 1 > v[i]) { 
       v[i] = v[j] + 1; 
       Pred[i] = j; 
      } 
      if (v[i] > v[imax]) { 
       imax = i; 
      } 
     } 
    } 
} 
void write() { 
    cout << " Longest Increasing Subsequence : "; 
    constituteSubsequence(imax); 
    cout << endl << " Length: " << v[imax]; 
} 
int main() { 
    read(); 
    calculate(); 
    write(); 
    return 0; 
} 

如果我运行这段代码,它编译和按预期工作,但如何这种状态何其它找到了一个0后价值(假),它打印cout < < a [i]? 。它何时停止?

+0

的可能的复制[解释这行代码做(http://stackoverflow.com/questions/35657778/explain-what-line-of-code-does) – Zulan

回答

2

在C++中,一个整数表达式可以被视为一个布尔值。例如,在if语句的上下文Pred[i] + 1意味着(Pred[i] + 1) != 0

这提供了回答你的问题:递归调用链将要结束的时候Pred[i]-1。当然,一个更容易阅读的方式来表达相同的条件下将与!=操作:

if(Pred[i] != -1) { 
    constituteSubsequence(Pred[i]); 
} 
+0

但是如果它在Pred [i]为-1之后停止,它如何在最长增加的子序列中打印所有数字? – poptartbr1