我正在尝试编写一个可以对任何给定的STL容器进行二进制搜索的函数(即列表,向量等)。我的方法是使用两个迭代器,一个用于序列的开头和结尾。
template <class ln, class T> int binarysearch_list(ln first, ln last, T search_value) {
int low = 0;
int high = 0;
int midpoint = 0;
int start = 0;
while(first != last) {
first++;
start++;
}
high = start;
while(low <= high) {
ln current = next(first, midpoint);
if(search_value == *current) { // if we already find search_value at the midpoint we can simply exit
return midpoint;
} else if(search_value > midpoint) {
low = midpoint + 1; // change the low to the next element after midpoint
} else if(search_value < midpoint) {
high = midpoint - 1;
}
}
return -1;
}
第一个while循环用于获取大小,第二个是实际二进制搜索。我在ln current = next(第一个,中点)得到一个错误,我不知道如何解决增量迭代器的问题。理想情况下,当您看到“if(search_value == * current)”时,它将像vector [midpoint]或list(midpoint)一样。我需要一种方法来使用开始和结束迭代器读取任何给定序列的第n个元素,我需要一种方法来通过n灵活地增加迭代器。我已经尝试了提前(第一,数量),(第一个+金额),还有很多其他人但是我很难过!