【发布时间】:2016-11-28 08:54:54
【问题描述】:
我正在研究迭代器,并且在弄清楚我们为什么要使用迭代器上被困了 3 天:
auto mid = text.begin() + (end - beg) / 2;
代码:
int main()
{
vector<int> text{ 10,9,8,7,6,5,4,3,2,1 };
int sought = 3;
// text must be sorted
// beg and end will denote the range we're searching
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg) / 2; // original midpoint
// while there are still elements to look at and we haven't yet found sought
while (mid != end && *mid != sought) {
if (sought < *mid) // is the element we want in the first half?
end = mid; // if so, adjust the range to ignore the second half
else // the element we want is in the second half
beg = mid + 1; // start looking with the element just after mid
mid = beg + (end - beg) / 2;// new midpoint
}
system("pause");
}
为什么
auto mid = text.begin() + (end - beg) / 2;
而不是:
auto mid = text.begin() + text.size() / 2;
请帮忙。
【问题讨论】:
-
我们是否使用“(end - begin)/2”?你在哪里找到的?
-
@Wolf - c++ 入门第 5 版。这有点误导,因为第 3.4 章的书说这是一个“经典算法”,所以我认为这是一种常见的情况(如果我错了,请纠正我)
-
之所以令人困惑,是因为该示例在 main 函数中实现了二分查找。如果它被正确地提取到一个只需要一个迭代器范围来搜索的函数中,那么为什么你不能在容器上调用 size 就很清楚了——因为你无法引用容器。
标签: c++ algorithm iterator binary-search