Copyright: code word is not easy, please indicate the source: https://blog.csdn.net/qq_24309981/article/details/90578276
Theory 1
Include files: #include <algorithm>
Namespace: a using namespace std;
function template:
template <class ForwardIterator>
ForwardIterator max_element (ForwardIterator first, ForwardIterator last);
template <class ForwardIterator, class Compare>
ForwardIterator max_element (ForwardIterator first, ForwardIterator last, Compare comp);
功能: Return largest element in range
- Returns an iterator pointing to the element with the largest value in the range [first,last), or last if the range is empty;
- The comparisons are performed using either operator< for the first version, or comp for the second;
- If more than one element fulfills this condition, the iterator returned points to the first of such elements.
The behavior of this function template is equivalent to:
template <class ForwardIterator>
ForwardIterator max_element ( ForwardIterator first, ForwardIterator last )
{
if (first==last) return last;
ForwardIterator largest = first;
while (++first!=last)
if (*largest<*first) // or: if (comp(*largest,*first)) for version (2)
largest=first;
return largest;
}
Example 2
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> nums = { 1,2,3,4,5,6,7,7 };
//区间为空,返回last,即nums.begin()
auto it = max_element(nums.begin(), nums.begin());
cout << *it << endl;
it = max_element(nums.begin(), nums.end());
//返回第一个7
cout << *it << endl;
it++;
//返回第二个7
cout << *it << endl;
//自定义比较函数
it = max_element(nums.begin(), nums.end(), [&](int a, int b) {return a > b; });
cout << *it << endl;
system("pause");
return 0;
}
//输出
1
7
7
1