设计一个函数模版find,用于对一个有序数组采用二分法查找指定数据的元素下标,用int, char型数据测试完整代码
时间: 2024-02-03 13:15:26 浏览: 83
下面是一个实现二分查找的函数模板 `find`,使用了 C++ 的迭代器(iterator)来遍历数组:
```cpp
#include <iostream>
#include <vector>
template<typename T>
int find(const std::vector<T>& arr, const T& target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
std::vector<int> arr1 = {1, 3, 5, 7, 9, 11, 13};
int target1 = 7;
int index1 = find(arr1, target1);
if (index1 != -1) {
std::cout << "Found " << target1 << " at index " << index1 << std::endl;
} else {
std::cout << "Could not find " << target1 << std::endl;
}
std::vector<char> arr2 = {'a', 'c', 'e', 'g', 'i', 'k', 'm'};
char target2 = 'g';
int index2 = find(arr2, target2);
if (index2 != -1) {
std::cout << "Found " << target2 << " at index " << index2 << std::endl;
} else {
std::cout << "Could not find " << target2 << std::endl;
}
return 0;
}
```
输出结果:
```
Found 7 at index 3
Found g at index 3
```
注意:这个函数模板要求输入的数组是有序的,否则可能得到错误的结果。
阅读全文