要在向量中找到中间项,为什么要使用 "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"

本文关键字:beg end mid 向量 为什么 中间      更新时间:2023-10-16

我是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 可避免溢出。

想象一下begMAX_INT-3endMAX_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?
相关文章: