for循环中的两个索引增量

hel*_*llo 2 c++ for-loop time-complexity

在阅读循环分析的文本时,我遇到了以下线性搜索例程,以返回数组中的最大值:

template <class otype>
int location_of_max (const otype a[], int first, int last)
{
    int max_loc = first; 
    for (++first; first <= last; ++first) {
        if (a[first] > a[max_loc]) {
            max_loc = first;
        }
    }

   return max_loc;
}
Run Code Online (Sandbox Code Playgroud)

++first相同的循环条件下有两个增量有点令人困惑.是否有一个原因?

Lig*_*ica 6

代码比较每个循环上的两个元素.

初始循环声明语句将"start"迭代器推进到第二个数组位置,因为"reference"元素(a[max_loc])作为第一个元素开始生命.

这避免了一个不必要的和无意义的比较(即a[max_loc] > a[max_loc]).