我尽量不使用任何存储容器。我不知道这是否可能。这是我到目前为止所拥有的。 (我遇到了段错误)。
#include <iostream>
#include <string>
using namespace std;
void foo(string s)
{
size_t pos;
pos = s.find(' ');
if(pos == string::npos)
return;
foo(s.erase(0, pos));
cout << s.substr(0, pos) << " ";
}
int main()
{
foo("hello world");
return 0;
}
我知道这段代码可能有很多问题。所以撕掉。我渴望学习。我正在尝试模仿后订单打印,就像您在单链表的反向打印中所做的那样。谢谢。
编辑: 一个例子: “你真了不起”变成了“你真了不起”
最佳答案
段错误是堆栈溢出。
foo( "hello world")
删除第一个空格 ("world"
) 之前的所有内容并递归。
foo( "world")
删除第一个空格 ("world"
) 之前的所有内容并递归。
foo( "world")
...你明白了。
此外,一旦您调用了 foo( s.erase( 0, pos ) )
,尝试在递归返回后打印 s.substr( 0, pos )
没有意义。您需要在删除之前将子字符串保存在某处,这样您仍然可以在之后打印它。
void foo(string s)
{
size_t pos = s.find(' '); // declare-and-use in one line
string out = s.substr( 0, pos ); // saving the substring
if ( pos != string::npos )
{
foo( s.erase( 0, pos + 1 ) ); // recurse, skipping the space...
cout << " "; // ...but *print* the space
}
cout << out; // print the saved substring
}
关于c++ - 通过递归倒序打印出一行中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34066133/