【STL】max_element()函数

函数功能:指向序列之中数组最大元素,包含在algorithm库中。

  • 函数返回迭代器,时间复杂度O(n)。

版本一

template<class ForwardIterator>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last)
{
    if(first == last)
        return first;
    ForwardIterator result = first; 
    while(++first != last)
        if(*result < *first)
            result = first;
    return result;
}

版本二

template<class ForwardIterator, class Compare>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last)
{
    if(first == last)
        return first;
    ForwardIterator result = first; 
    while(++first != last)
        if(comp(*result , *first))
            result = first;
    return result;
}

运用实例:
Leetcode 969. Pancake Sorting
参考书籍

  • 《STL源码剖析》

猜你喜欢

转载自www.cnblogs.com/zuotongbin/p/10235552.html
今日推荐