Блог пользователя Coding_master_guy

Автор Coding_master_guy, 3 года назад, По-английски

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;
}

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
3 года назад, # |
  Проголосовать: нравится +14 Проголосовать: не нравится

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

»
3 года назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

try to make like this:

void reverse(string &s, int start,int end)
  • »
    »
    3 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    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 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      Because all arrays are automatically passed by reference by default.

    • »
      »
      »
      3 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      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