设计一个函数模版find,用于对一个有序数组采用二分法查找指定数据的元素下标,用int, char型数据测试完整代码
时间: 2024-02-03 21:15:14 浏览: 26
下面是实现二分查找的C++代码,其中使用了函数模板 `find`:
```C++
#include <iostream>
#include <cstring>
using namespace std;
template<typename T>
int find(T arr[], int n, T target) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
int main() {
int intArr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char charArr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
int n = sizeof(intArr) / sizeof(int);
char m = sizeof(charArr) / sizeof(char);
int target1 = 3;
char target2 = 'e';
int pos1 = find(intArr, n, target1);
int pos2 = find(charArr, m, target2);
if (pos1 != -1)
cout << "The position of " << target1 << " in array is: " << pos1 << endl;
else
cout << target1 << " is not in the array." << endl;
if (pos2 != -1)
cout << "The position of " << target2 << " in array is: " << pos2 << endl;
else
cout << target2 << " is not in the array." << endl;
return 0;
}
```
这个函数模板接收三个参数:一个有序数组 `arr`,数组的元素个数 `n`,和要查找的目标元素 `target`。函数返回目标元素在数组中的下标,如果没找到则返回 `-1`。
在主函数中,我们声明了两个数组:`intArr` 和 `charArr`,分别存储了整型数据和字符型数据。我们使用 `sizeof` 函数计算了数组的长度,然后分别调用了 `find` 函数,查找了整型数据 `3` 和字符型数据 `'e'` 在数组中的位置。
运行程序,输出结果如下:
```
The position of 3 in array is: 2
The position of e in array is: 4
```
可以看到,我们成功地使用了函数模板 `find` 对有序数组进行了二分查找,找到了目标元素在数组中的位置。