Help me find a problem with this line: rev(s[1..s.length]);

I am struggling to understand RECURSION:
This line is in this recursive function:

1
2
3
4
5
6
  void rev(string s) {
  if (!s.empty()) {
    rev(s[1..s.length]);
  }
  print(s[0]);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

void print_reverse( const std::string& s ) {

    if( !s.empty() ) {

        // print the reverse of all characters in the string other than the first character
        // pseudocode: print_rev( s[1..s.length] )
        // C++ code: print the reverse of the substring starting at position 1
        print_reverse( s.substr(1) ) ;

        // after that print the first character
        // pseudocode: print( s[0] )
        std::cout << s.front() ; // C++ code: print the first character
    }
}

int main()
{
    const std::string str = "hcstueD reteP - enivid esrucer ot ,namuh si etareti oT" ;
    std::cout << str << "\n\n" ;

    print_reverse(str) ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/6c0ca4fd88b8602e
Topic archived. No new replies allowed.