簡介
在做項目或刷題的過程中,經常需要返回數組的最大值和最小值。
若自己寫會有一些麻煩,因此可以用C++ STL庫 *max_element() 和 *min_element() 函數來返回數組的最大值和最小值。
注:
需引入頭文件:
#include<algorithm>
max_element()函數
函數官方定義
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;
}
舉例說明
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };
vector<int>vec(array, array + 10);
cout << *max_element(array, array + 10) << endl;
cout << *max_element(vec.begin(), vec.end()) << endl; //輸出結果均爲:87
system("pause");
return 0;
}
min_element()函數
函數官方定義
template <class ForwardIterator>
ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
if (first==last) return last;
ForwardIterator smallest = first;
while (++first!=last)
if (*first<*smallest) // or: if (comp(*first,*smallest)) for version (2)
smallest=first;
return smallest;
}
舉例說明
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };
vector<int>vec(array, array + 10);
cout << *min_element(array, array + 10) << endl;
cout << *min_element(vec.begin(), vec.end()) << endl; //輸出結果均爲:9
system("pause");
return 0;
}
參考資料
http://www.cplusplus.com/reference/algorithm/min_element/
http://www.cplusplus.com/reference/algorithm/max_element/