C++ 这个代码怎么能颠倒过来?(递归)
从Pierre Fourgeaud(互联网)那里得到了代码,但我不明白它是如何被逆转的C++ 这个代码怎么能颠倒过来?(递归),c++,visual-c++,recursion,C++,Visual C++,Recursion,从Pierre Fourgeaud(互联网)那里得到了代码,但我不明白它是如何被逆转的 void reverse( string& word ) { if ( word.size() <= 1 ) return; // Get the string without the first and the last char string temp = word.substr( 1, word.size() - 2 ); // Reverse it
void reverse( string& word )
{
if ( word.size() <= 1 ) return;
// Get the string without the first and the last char
string temp = word.substr( 1, word.size() - 2 );
// Reverse it
reverse( temp );
// Recompose the string
word = word.substr( word.size() - 1 ) + temp + word[0];
}
void reverse(字符串和单词)
{
如果(word.size()显然,是递归让您感到困惑。因此,下面是一个示例:
string word = "world";
- 第一个递归将
“world”
拆分为:“w”、“orl”和“d”
,并将“orl”
传递给第二个递归。
- 第二个递归将
“orl”
拆分为:“o”、“r”和“l”
,并将“r”
传递给第三个递归。
- 第三个递归将不起任何作用,因为它计算“r”的大小,同时也反转中间。有什么问题吗?什么是“It”;为什么你不理解“It”是如何反转的?