19. Find function elements (recursive method)

topic:

Preparation of a template recursive function, determines whether the array element x a [0: n - 1].

Ideas:

The title does not say the orderly array, then the default is disorderly array should look linear. At the same time is recursive, it should be from the beginning or end of a comparison of a return to find equal, otherwise the recursive call function, passing the parameter is an array, and a small number of elements.

Function exits of two conditions:

1. When the number of elements is less than 0, indicating that the target element from the array, not found.

2. Find success.

Code:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <typename T>
 5 bool is_find (const T* a, int n, const T& target) {
 6     if (n - 1 < 0) {
 7         return false;
 8     }
 9     if (a[n - 1] == target) {
10         return true;
11     } else {
12         return is_find(a, n - 1, target);
13     }
14 }
15 
16 int main()
17 {
18     int a[5] { 0, 1, 2, 3, 4 };
19     int target;
20     cout << "Enter target : ";
21     cin >> target;
22     bool found = is_find(a, 5, target);
23     cout << "result : " << found << endl;
24 
25     return 0;
26 }

There are several code should be noted:

1. The boundary condition function is n - 1 <0. For example: the array a, comprising five elements, but the last element index is 4. When there remains an array element at index 0, then n - 1 = 0, when no element in the array, n - 1 = -1 <0, indicating no found.

2. Incoming array declared as const, because they do not change their elements; target element declared as const &, is the same reason.

 

Guess you like

Origin www.cnblogs.com/Hello-Nolan/p/12342964.html