前面的博客已經講解了nth_element尋找區間第K大的用法,現在我們來說說這兩個找區間最值的用法。兩個函數都包含在algorithm庫中。
一、函數原型
- 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——自定義比較函數
顧名思義,max_element就是求區間最大值,而min_element就是求區間最小值。當然也可以自定義比較函數達到自己想要的“最大值”或者“最小值”
二、代碼演示
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 }
預計上面代碼輸出為5 1,但是最終卻編譯錯誤。Why?
因為這兩個函數返回的是最大值或者最小值的迭代器,所以我們得加上一個*號得到值,最終代碼如下:
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 */
三、手動實現
這兩個函數手動實現就很簡單了,直接遍歷一遍找最值即可,這里貼一下cppreference上的源碼實現:
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 }
四、復雜度分析
比較n-1次,n是區間長度,時間負責度為O(n)。