Coding_master_guy's blog

By Coding_master_guy, 3 years ago, In English

i want to recursively reverse a string in c++ but this code only swaps first and last characters of the string and leave other characters as it is

#include <iostream>
#include<string>

using namespace std;

string reverse(string s, int start,int end)
{
    if(start < end)
    {
        swap(s[start] , s[end]);
        reverse(s , start +1 , end -1);
        
    }

     return s;
    
}

int main()
{
   string s;
   cin>>s;
   
   cout<<reverse(s,0,(s.length() -1));

    return 0;
}

| Write comment?
»
3 years ago, # |
  Vote: I like it +14 Vote: I do not like it

reverse(s, start+1, end-1) -> return reverse(s, start+1, end-1)

»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

try to make like this:

void reverse(string &s, int start,int end)
  • »
    »
    3 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    thanks i didnot think about pass by reference.

    But if we donot need to return character array or any type of array then why we need to return or pass by reference in case of "string" ?

    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Because all arrays are automatically passed by reference by default.

    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Using a call-by-value to an object parameter whose data size is large in recursive function declaration is not recommended in C++. The reason is that the C++ compiler creates a new copy of the called parameter object, and then pushes the starting address of this new object to the calling parameters stack. In your call-by-value reverse function, this means that the program requires $$$O(N^2)$$$ dynamic memory to reverse an $$$N$$$-character string. Check the execution time and memory requirements of call-by-value and call-by-reference of your updated program.

      Call-by-value

      Call-by-reference