本文介紹了C++中的尾遞歸的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
誰能給我看一個簡單的 C++ 尾遞歸函數?
Can someone show me a simple tail-recursive function in C++?
為什么尾遞歸更好,甚至更好?
Why is tail recursion better, if it even is?
除了尾遞歸還有哪些遞歸?
What other kinds of recursion are there besides tail recursion?
推薦答案
一個簡單的尾遞歸函數:
A simple tail recursive function:
unsigned int f( unsigned int a ) {
if ( a == 0 ) {
return a;
}
return f( a - 1 ); // tail recursion
}
尾遞歸基本上是在:
- 只有一個遞歸調用
- 那個調用是函數中的最后一個語句
而且它并不是更好",除非一個好的編譯器可以刪除遞歸,將其轉換為循環.這可能更快,并且肯定會節省堆棧使用量.GCC 編譯器可以進行這種優化.
And it's not "better", except in the sense that a good compiler can remove the recursion, transforming it into a loop. This may be faster and will certainly save on stack usage. The GCC compiler can do this optimisation.
這篇關于C++中的尾遞歸的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!