C++ 标准库 - <algorithm>

C++ std::max_element 返回区间中最大元素的迭代器;空区间返回 last。

原型

template<class ForwardIt>
ForwardIt max_element(ForwardIt first, ForwardIt last);

参数

  • first, last:搜索区间。

返回值

指向最大元素的迭代器;并列最大值取最先出现者。空区间为 last。

示例

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {4, 9, 3, 9};
    auto it = std::max_element(v.begin(), v.end());
    if (it != v.end()) {
        std::cout << *it << std::endl;
    }
    return 0;
}

输出:

9

注意事项

<algorithm> 本批到此结束。累加、内积等见 <numeric>。可返回函数总览或标准库概览,并在在线编译器中改参数继续试验。

下一组头文件见<iostream>。教学章节可从STL 算法概览对照阅读。