要在向量中找到中间项,为什么要使用 "mid = beg + (end - beg) / 2" 而不是 " mid = (beg + end) /2"
to find the middle item in a vector, why use "mid = beg + (end - beg) / 2" instead of " mid = (beg + end) /2"
我是C++新手。我在网上看到了这段代码,它试图在向量中找到一个字符串。但是,我在最后注意到:
mid = beg + (end - beg) / 2;
为什么一定要这样写,为什么不能写成:
mid = (beg + end) /2
mid = (beg + (end - 1)) / 2
是一个可行的替代方案吗?
我正在努力理解它背后的原因。
vector<string> text = {"apple", "beer", "cat", "dog"};
string sought = "beer";
auto beg = text.begin(), end = text.end();
auto mid = text.begin() + (end - beg) / 2;
while (mid != end && *mid != sought){
if(sought < *mid){
end = mid;
} else {
beg = mid + 1;
}
mid = beg + (end - beg) / 2;
}
通常,对于二进制搜索,原因是为了避免溢出。 beg+end
可能会因大值而溢出。 使用 end-beg
可避免溢出。
想象一下beg
是MAX_INT-3
,end
是MAX_INT-1
,那么beg+end
会比MAX_INT
大,但end-beg
,只会是2。
对于迭代器,这也有效,因为end-begin
是一个数字,而begin+end
无效。 您可以减去两个迭代器来获得它们之间的距离,但不能添加两个迭代器。
添加两个迭代器没有意义,您也不能这样做。
您可以在两个迭代器上调用operator-
,并给出合理的结果,即两个迭代器之间的元素计数。你可以在迭代器上加减一个整数,意味着向前或向后移动它。但是添加两个迭代器的结果应该是什么?
mid = beg + (end - beg) / 2;
~~~~~~~~~~ => get the count between beg and end
~~~~~~~~~~~~~~~ => get the half of the count
~~~~~~~~~~~~~~~~~~~~~ => get the iterator pointing to the middle position between beg and end
mid = (beg + end) /2
~~~~~~~~~ => What would the result represent?
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 反转依赖于 end() 的迭代器
- std::multimap<std::chrono::milliseconds, T>::rbegin 在 MSVS-13 中指向 end()?
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- remove(str.begin(), str.end(), );无法正常工作(我正在使用视觉工作室 2012)
- 在 ifcondition al中 find() C++ STL 中的 == a.end() 有什么用?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 了解向量中的 .begin 和 .end
- 如何实现链表的 end()?
- 使用 map.end() 访问 map 的最后一个元素
- C++ const char with .begin() and .end()
- 接收"Error compiling: 0:1(1): error: syntax error, unexpected $end" C++、GLSL、着色器文件
- 为什么 std::find( s.begin(), s.end(), val ) 比集合 s 的 s.find(val) 慢 1000 倍<int>?
- 如何使用vector.begin()和vector.end()遍历矩阵?
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- 创建一个简单的前向迭代器,该迭代器在循环缓冲区的"end"处自动换行
- 在二叉搜索中,mid=(beg+end)/2 和 mid=beg+(end-beg)/2 有什么区别?
- 要在向量中找到中间项,为什么要使用 "mid = beg + (end - beg) / 2" 而不是 " mid = (beg + end) /2"