0

私はいくつかの再帰的な演習を行っています。前のものは、基本的に最初の文字を削除してからソリューションを組み合わせる文字列の reverse() 関数を作成することでした。これがソースコードです (ソース全体) 現在のタスクは、文字列の部分文字列を逆にするヘルパー関数を追加して、この関数を変更することです (本の次の演習)。現時点では、私はこれで立ち往生しています。追加の引数などを渡す必要があるときにヘルパー関数を使用すると理解していますが、この関数は何も受け取らないため、この問題に対処する方法が本当にわかりません。助けていただければ幸いです。

    #include <iostream>
    #include <string>
    using namespace std;

    void reverse(string& text)
    {
        if (text.length() == 0)
        {
            return;
        }
        if (text.length() == 1)
        {
            return;
        }
        else
        {
            string firstLetter = text.substr(0,1);
            text = text.substr(1, text.length()-1);
            reverse(text);
            text += firstLetter;
            }
    }
    int main()
    {
        string a = "tyu";
        reverse(a);
        cout << a << endl;
        return 0;
    }

パラメータを使用するように提案された男、ect、これは私の試みです:

#include <iostream>
#include <string>
using namespace std;
//is actually doing the hard work
void reverse1(string& input, int a, int b)
{
        // base case
        if( a >= b)
        {
             return;
        }
        //swap the characters
        char tmp;
        tmp = input[a];
        input[a] = input[b];
        input[b] = tmp;
        //create the boundries for the new substring
        a++;
        b--;
        //call the function again
        reverse1(input, a, b);
}

// sets the parameters and calls the helper function
void strreverse(string& input)
{

    reverse1(input, 0, input.length()-1);
}

int main()
{
    cout << "Please enter the string which you want to be reversed:";
    string a;
    cin >> a;
    strreverse(a);
    cout << a << endl;
    return 0;
}
4

3 に答える 3