前面的博客已經講解了nth_element尋找區間第K大的用法,如今咱們來講說這兩個找區間最值的用法。兩個函數都包含在algorithm庫中。c++
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 );
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 );
first,end——區間範圍函數
comp——自定義比較函數spa
顧名思義,max_element就是求區間最大值,而min_element就是求區間最小值。固然也能夠自定義比較函數達到本身想要的「最大值」或者「最小值」code
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?blog
由於這兩個函數返回的是最大值或者最小值的迭代器,因此咱們得加上一個*號獲得值,最終代碼以下: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 } 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)。源碼