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 count occurrences of a character in a string # include <iostream>#include <cstring>//The header file where the character lookup function STRCHR () is introducedUsingNamespaceStd//To implement the number of occurrences of a statistical character in a string using recursive invocation of a functionint Countchar (Constchar* STR,ConstCharc) {//Find the character C from the beginning of the string strchar* 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 0if (nullptr = =POS) {Return0; }//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 functionsReturn1 + countchar (pos +1, c);}IntMain () {//StringChar str[] ="Thought is a seed";char C =‘H‘;//Target character// call the Countchar () function for statistics int ncount = Countchar (str,c); // output Cout<< " Span style= "color: #800000;" > character \ ' ' <<c<< ' \ "in \" "<<str<< " "<< Ncount<< "" <<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 structureint Countchar (Constchar* str,const char< Span style= "color: #000000;" > c) {int ntotal = 0; // record character occurrences // Find the character in the string and judge the result // if STRCHR () returns NULLPTR, the search is complete. Loop End while (nullptr! = (str = STRCHR (str,c))) {++ntotal; Span style= "color: #008000;" >// The characters to be found are counted ++str; // " Span style= "color: #0000ff;" >return Ntotal;}
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.
Original address: http://www.cnblogs.com/nihaoCPP/p/4191327.html
Hello, C + + (27) Call it itself within a function recursive invocation of its own 5.1.5 function