Hello, C + + (27) Call it itself within a function recursive invocation of its own 5.1.5 function

Source: Internet
Author: User

Recursive invocation of the 5.1.5 function

In a function call, we usually call another function in one function to accomplish some of these functions. For example, we call the Powersum () function in main () main function to calculate the sum of squares of two numbers, and in the Powersum () function, the power () function and the Add () function are called to calculate the square of each number and the sum of two squares to be the final result. In addition, there is another special method of function invocation in C + +, which is to invoke itself within a function, which is also called recursive invocation of functions.

Recursive invocation of functions is actually a special way of implementing a function. When a recursive function is called, it produces a loop that calls itself, and the loop continues recursively until the last function call is under special conditions, that is, the recursive termination condition is satisfied, and no longer calls itself but returns a specific result data. At this point, all the upper functions that call this function are returned in turn until we initially return the call to the function to get the result data. Although the recursive invocation of a function is self-invoking each time, the conditions of each recursive invocation, that is, the function parameters, are often different. It is the change in the invocation condition that makes it possible for the function to satisfy the terminating condition and return a concrete result data, no longer recursively calling itself, which is the end of the recursive call.

The recursive invocation of a function is complex in form, but it deals with a problem that can break a big problem into a known result and a similar one, needing to repeat several times to do something similar in order to finally solve the problems, because the recursive invocation of the function itself expresses the meaning of doing the same thing in a cyclical way, So there is a natural advantage in dealing with this kind of problem. For example, we want to count the number of occurrences of a character in the target string. In general, our idea is to use a for loop to iterate through the entire character array and then match the statistics by character. And if the idea of recursive function to solve this problem, then the entire statistical process will become: from the beginning of the target string to find the character, if found, then the number of occurrences of the character has been found this time plus the number of occurrences in the remaining string, in the program we can use "1 + Countchar (pos+1, C) ", where" 1 "means that the character that has been found appears once, and" Countchar (pos+1, C) "represents the number of times the character appears in the remaining string, plus exactly how many times the character appears in the entire string. The "Countchar (pos+1, C)" Here is the recursive invocation of the Countchar () function after the change start condition, and the second lookup and statistics. The second lookup will also perform a similar lookup statistics process, and if found, it will call the Countchar () function for the third time to continue to look for statistics backwards. This process continues continuously until the end of the recursive condition is satisfied--the end of the string is found, and the character is not found--so far. In this process, there are the same actions that need to be performed in a repeating cycle-looking for the target character from the beginning of the string, a different starting condition-starting at a different position in the string, terminating condition-the target character can no longer be found in the string. With these three features, we can solve this problem more easily and naturally with recursive invocation of functions:

//Countchar.cpp Statistics The number of occurrences of a character in a string#include <iostream>#include<cstring>//the header file where the character lookup function STRCHR () is introducedusing namespacestd;//To implement the number of occurrences of a statistical character in a string using recursive invocation of a functionintCountchar (Const Char* STR,Const Charc) {    //find the character C from the beginning of the string str    Char* pos =STRCHR (STR,C); //if the return value of the STRCHR () function is nullptr, it means//The target character cannot be found in the string, and the terminating condition of the recursion is satisfied//The recursive call to the End function returns the results of this search 0    if(nullptr = =POS) {        return 0; }    //if the termination condition is not met, the results of this finding 1 are counted,//and at the new start position pos + 1 begins the next lookup, implementing recursive invocation of functions    return 1+ Countchar (pos +1, c);}intMain () {//string    CharStr[] ="thought is a seed"; Charc ='h';//Target character//Call the Countchar () function for statistics    intNcount =Countchar (STR,C); //Output Resultscout<<"character \ '"<<c<<"\ ' in \ '"<<str<<"\ "appears in the"<<nCount<<"Times"<<Endl; return 0;}

During execution, when Countchar () is first called in the main function, the first parameter str points to the string "thought is a seed", at which point the Countchar () function executes and the STRCHR () function finds the character ' H ' appears and is saved to the character pointer Pos, which does not yet meet the termination condition (nullprt = = pos), then executes "return 1 + countchar (pos+1,c)", the results of this search are counted, and the starting condition of the change recursion is "pos+1", Let the second recursive call the Countchar () function when the string that the parameter str points to becomes "ought is a seed". When the second entry into the Countchar () function executes, the STRCHR () function will find the second occurrence of the character ' H ', and the terminating condition of the recursion will still not be satisfied, then continue to count the results of this search and modify the start condition to point to the str parameter of the Countchar () function "T is a seed", starting the third recursive call. The third time the Countchar () function executes, the STRCHR () function can no longer find the target character in the remaining string, the terminating condition of the recursion is satisfied, the function returns the lookup statistic result 0 (return 0;), and no longer continues to recursively invoke Countchar ( ) function, and then return from layer to row, eventually ending the entire function recursive call process, resulting in the final result 2, which is the number of occurrences of the target character in the string. The entire process is shown in 5-8.

Figure 5-8 Recursive call procedure for Countchar () function

The function of recursive invocation, the essence of a big problem is constantly broken down into a number of similar small problems, and then through the continuous subdivision, until the small problem is resolved, to finally solve the biggest problem at the beginning. For example, in this case, the big question we start with is the number of target characters in the statistics string, and then the big problem is broken down to the number of target characters currently found in 1 and the number of target characters in the remaining string Countchar (Pos+1,c), and we want to calculate the number of target characters in the remaining string, You can further subdivide with the same strategy until there are no target characters in the remaining string and cannot continue to subdivide. From here we can also see that the recursive invocation of a function is actually a looping process, and we must ensure that the function can reach its recursive termination condition and end the recursion. For example, we are constantly adjusting the start position of the lookup so that we can never find the target character and meet the termination criteria. Otherwise, the function is recursively called indefinitely, eventually forming an infinite loop and never getting the result. This is especially important when designing recursive functions.

Recursive invocation of a function is accomplished by invoking itself in a function in a recurrent way, in essence, the recursive invocation of a function is actually a special form of looping. Therefore, we can also implement recursive invocation of a function instead of a loop structure. For example, the Countchar () function above can be rewritten with a looping structure:

//the number of times a statistical character appears in a string using a looping structureintCountchar (Const Char* STR,Const Charc) {    intNtotal =0;//Record character Occurrences//look up a character in a string and judge the result//if STRCHR () returns NULLPTR, it means that the search is complete and the loop ends     while(nullptr! = (str =STRCHR (str,c))) {          ++ntotal;//count the found characters++STR;//string moves backwards, starting the next loop    }    returnntotal;}

Here we cannot help but ask, since recursive invocation of functions can be implemented with a loop structure, and the recursive invocation of functions involves the function call of those passing parameters to protect the scene behind the scenes, performance is relatively low, then why should we use the recursive invocation of the function instead of directly using a more efficient loop structure to solve the problem? This is because, in the face of certain special problems, it is very difficult for us to solve the cyclic structure. For example, from an array to find the continuous and value of the largest data series, if the use of circular structure, we almost impossible, even if the final solution but the performance is very low. And this problem can be broken down into a number of similar small problems, such as here we can divide the array into the left and right parts, then the largest value of the data series is either on the left side, or on either side, or across two parts. In this way, the problem is subdivided into three similar minor problems that look for the left-hand, right-side, and maximum-value sequences that span both sides. And these three small problems can be further refined, until the last can be easily solved the smallest problem. In this case, the use of recursive invocation of functions to solve the problem, more in line with our human thinking, the problem is easier to solve, while its performance will be better than the implementation of the circular structure, so that "good and fast." Solving this kind of special problem that can be broken down continuously is the function of recursive invocation.

Hello, C + + (27) Call it itself within a function recursive invocation of its own 5.1.5 function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.