2 回答

TA貢獻1829條經驗 獲得超7個贊
#include <algorithm> // 頭文件
template <class T>
const T& max ( const T& a, const T& b );
template <class T, class Compare>
const T& max ( const T& a, const T& b, Compare comp );
有以上兩種函數原型. 上面那個使用了模版T, 下面那個還使用了比較類
用法 max(a,b) 或者 max(a,b,comp)
其中a和b是可比較的兩個元素, 函數返回比較大的那個

TA貢獻1951條經驗 獲得超3個贊
函數:
template <class T> const T& max ( const T& a, const T& b ) {
return (b<a)?a:b; // or: return comp(b,a)?a:b; for the comp version
}
例子:
// max example
#include <iostream>
#include <algorithm>
using namespace std;
int main () {
cout << "max(1,2)==" << max(1,2) << endl;
cout << "max(2,1)==" << max(2,1) << endl;
cout << "max('a','z')==" << max('a','z') << endl;
cout << "max(3.14,2.72)==" << max(3.14,2.72) << endl;
return 0;
}
添加回答
舉報