c++ - 通过递归倒序打印出一行中的单词

标签 c++

我尽量不使用任何存储容器。我不知道这是否可能。这是我到目前为止所拥有的。 (我遇到了段错误)。

#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/

相关文章:

c++ - Qt QTextEdit 添加虚假行

c++ - 为不阻塞且可以重用的子进程创建非阻塞管道

c++ - 将字符串转换为int的简单方法? C++

c++ - 在 C++ 中不能内联虚函数总是正确的吗?

c++ - 如何使用包含非拉丁字符的 C++ 程序?

c++ - 在 magick++ api 中调整大小的默认过滤器类型

c++ - 查询 C++ 迭代器标记

c++ mysql在数据库中插入

c++ - 即使该构造无法编译,对象构造表达式是否格式良好?

c++ - 努力从 Eclipse IDE 中将我的 C++ 项目作为单个可执行文件发布