3

For my void function reverse, I have to get a string and reverse it with recursion.

So far, I have

void reverse(string &s)
{
    string b = s;
    s = s.substr(1) + s.at(0);
}

but it won't work because of the pass by reference requirement for the function. How do I utilize the pass by reference for recursion?

9
  • Do you have to pass by reference? Commented Mar 6, 2014 at 2:49
  • Yes, it has to be pass by reference. Commented Mar 6, 2014 at 2:51
  • Post your real code. s has no type so the rest of your code is suspect. reverse does not return a value but you expect it to. Commented Mar 6, 2014 at 2:54
  • 1
    How is this recursive. Not calling reverse within reverse Commented Mar 6, 2014 at 3:04
  • 1
    @EricFortin - Wish people would not do that - makes the comments/answers meaningless. Commented Mar 6, 2014 at 3:08

2 Answers 2

5

For the record, here's what the function was when I answered:

void reverse(string &s)
{
    s = reverse(s.substr(1)) + s.at(0);
}

Multiple problems here:

First you are adding the result of reverse with a char. reverse returns void so this doesn't work. Second, substr creates a new string and passing a temp by reference is asking for trouble. Finally, in recursion, you need an exit condition. As it is, your method is crashing trying to get a substr when length is 1.

Here's a version that works:

void reverse(string &s)
{
    if (s.size() == 1)
        return;

    string sub = s.substr(1);
    reverse(sub);
    s = sub + s.at(0);
}
Sign up to request clarification or add additional context in comments.

3 Comments

How does the function end its loop with s.size? Wouldn't s stay at the size of the input?
If length of string to reverse is 1, the reverse is the same string so don't call reverse on it again or it will recurse forever.
I see. So for s = sub + s.at(0);, the function terminates as sub empties out? I was having problems with an infinite loop as it kept reversing nonstop.
0

What about:

void _reverse(string& s, size_t z0, size_t z1)
{
    if (z1 <= z0)
        return;

    auto aux = s[z0];
    s[z0] = s[z1];
    s[z1] = aux;
    _reverse(s, z0 + 1, z1 - 1);
}


void _reverse(string& s)
{
    _reverse(s, 0, s.length() - 1);
}


int main()
{
    string x = "hello my friend";
    _reverse(x);
    cout << x << endl;
}

3 Comments

At the very least use std::swap to swap the values.
I can only use the given function, reverse for this assignment.
No loops and no iterators as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.