我一直致力于实现堆算法的递归版本。这是伪代码的链接:http://en.wikipedia.org/wiki/Heap%27s_algorithm
在我到达递归部分之前,一切都进行得很顺利。我知道我还没有放入交换元素,但我还没有走那么远。运行失败但没有显示错误,直到我使用 gcc 调试器告诉我存在段错误。这是我的代码:
#include <string>
#include <iostream>
using namespace std;
string* permute(int n, string array[2]){
if (n==1){
return array;
}
else{
for(int c=1; c<=n;c++){
permute(n--,array);
}
}
}
int main() {
string array[2]={"a","b"};
permute(2,array);
return 0;
}
最佳答案
撇开整个实现似乎错误这一事实不谈,您遇到运行时异常的直接原因是您对 permute(2,array)
的递归调用,这最终会导致堆栈溢出。发生这种情况是因为您使用 n--
而不是 --n
(或更准确地说,n-1
)调用它。
关于c++ - C++段错误中的堆算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24613106/