程序填空题:基于迭代器的折半查找
下述程序中的binarySearch()函数是一个基于迭代器的折半查找函数。请结合程序上下文将其补充完整。
c++
#include <iostream>
#include <vector>
using namespace std;
template <typename T, typename V>
T binarySearch(T begin, T end, const V v){
auto endOriginal = end;
while () {
if (*mid==v)
return mid;
else if (v < *mid)
end = mid;
else
}
return endOriginal;
}
int main() {
vector<int> a {1,3,5,7,9,11,22,77,88,100,999,2132,6789};
int v;
cin >> v;
auto r = binarySearch(a.cbegin(),a.cend(), v);
if (r==a.cend())
cout << "Not found." << endl;
else
cout << "Found: " << *r << endl;
return 0;
}
<br>**拼尽全力还是不会?参考B站习题讲解**<br>哔哩哔哩up主:[海洋饼干叔叔](https://space.bilibili.com/384177380) [Python课程](https://www.bilibili.com/video/BV1kt411R7uW/) [Python习题](https://www.bilibili.com/video/BV1iL411t7UZ/)[简洁的C和C++](https://www.bilibili.com/video/BV1it411d7zx/)作者每天分享一篇关于C/C++/Python的技术文章,学习编程不迷路。![image.png](~/7c4cfd2d-8e3e-40cd-826d-299d4200e600.png)
答案:
第1空:begin != end
第2空:auto mid = begin + (end-begin)/2;
第3空:begin = mid+1;
c++
#include <iostream>
#include <vector>
using namespace std;
template <typename T, typename V>
T binarySearch(T begin, T end, const V v){
auto endOriginal = end;
while () {
if (*mid==v)
return mid;
else if (v < *mid)
end = mid;
else
}
return endOriginal;
}
int main() {
vector<int> a {1,3,5,7,9,11,22,77,88,100,999,2132,6789};
int v;
cin >> v;
auto r = binarySearch(a.cbegin(),a.cend(), v);
if (r==a.cend())
cout << "Not found." << endl;
else
cout << "Found: " << *r << endl;
return 0;
}
<br>**拼尽全力还是不会?参考B站习题讲解**<br>哔哩哔哩up主:[海洋饼干叔叔](https://space.bilibili.com/384177380) [Python课程](https://www.bilibili.com/video/BV1kt411R7uW/) [Python习题](https://www.bilibili.com/video/BV1iL411t7UZ/)[简洁的C和C++](https://www.bilibili.com/video/BV1it411d7zx/)作者每天分享一篇关于C/C++/Python的技术文章,学习编程不迷路。![image.png](~/7c4cfd2d-8e3e-40cd-826d-299d4200e600.png)
答案:
第1空:begin != end
第2空:auto mid = begin + (end-begin)/2;
第3空:begin = mid+1;