# 一、函数原型

• max_element

1 template< class ForwardIt >
2 ForwardIt max_element(ForwardIt first, ForwardIt last );
3 template< class ForwardIt, class Compare >
4 ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp );
• min_element
1 template< class ForwardIt >
2 ForwardIt min_element( ForwardIt first, ForwardIt last );
3 template< class ForwardIt, class Compare >
4 ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp );

## 1.参数

first，end——区间范围

comp——自定义比较函数

# 二、代码演示

1 #include <bits//stdc++.h>
2 using namespace std;
3
4 int main(){
5     int a[] = {1,2,3,4,5};
6     int maxa = max_element(a,a+5), mina = min_element(a,a+5);
7     cout << maxa << ' ' << mina << endl;
8     return 0;
9 }

 1 #include <bits//stdc++.h>
2 using namespace std;
3
4 int main(){
5     int a[] = {1,2,3,4,5};
6     int maxa = *max_element(a,a+5), mina = *min_element(a,a+5);
7     cout << maxa << ' ' << mina << endl;
8     return 0;
9 }
10
11 /**运行结果
12 5 1
13 */

# 三、手动实现

 1 //版本一
2 template<class ForwardIt>
3 ForwardIt max_element(ForwardIt first, ForwardIt last)
4 {
5     if (first == last) {
6         return last;
7     }
8     ForwardIt largest = first;
9     ++first;
10     for (; first != last; ++first) {
11         if (*largest < *first) {
12             largest = first;
13         }
14     }
15     return largest;
16 }
17
18 //版本二
19 template<class ForwardIt, class Compare>
20 ForwardIt max_element(ForwardIt first, ForwardIt last,
21                       Compare comp)
22 {
23     if (first == last) {
24         return last;
25     }
26     ForwardIt largest = first;
27     ++first;
28     for (; first != last; ++first) {
29         if (comp(*largest, *first)) {
30             largest = first;
31         }
32     }
33     return largest;
34 }

# 四、复杂度分析

posted @ 2018-12-29 12:49  Xenny  阅读(2647)  评论(0编辑  收藏