1. 簡(jiǎn)介
函數(shù) |
作用 |
文檔 |
max(a,b) |
返回兩個(gè)元素中較大一個(gè)锥惋。 |
max() |
max(a,b,cmp) |
使用自定義比較操作cmp ,返回兩個(gè)元素中較大一個(gè)馒铃。 |
max() |
max_element(beg,end) |
返回一個(gè)ForwardIterator ,指出[beg ,end )中最大的元素煌珊。 |
max_element() |
max_element(beg,end,cmp) |
使用自定義比較操作cmp ,返回一個(gè)ForwardIterator ,指出[beg ,end )中最大的元素泌豆。 |
max_element() |
min(a,b) |
返回兩個(gè)元素中較小一個(gè)定庵。 |
min() |
min(a,b,cmp) |
使用自定義比較操作cmp ,返回兩個(gè)元素中較小一個(gè)。 |
min() |
min_element(beg,end) |
返回一個(gè)ForwardIterator 踪危,指出[beg ,end )中最小的元素蔬浙。 |
min_element() |
min_element(beg,end,cmp) |
使用自定義比較操作cmp ,返回一個(gè)ForwardIterator ,指出[beg ,end )中最小的元素陨倡。 |
min_element() |
2. 示例代碼
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
bool StrComp(const char* a,const char* b){
return strcmp(a,b)<0;
}
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.73)==" << max(3.14,2.73) << endl;
cout << "max(\"123\",\"abc\")==" << max("123","abc",StrComp) << endl;
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
bool StrComp(const char* a,const char* b){
return strcmp(a,b)<0;
}
int main () {
cout << "min(1,2)==" << min(1,2) << endl;
cout << "min(2,1)==" << min(2,1) << endl;
cout << "min('a','z')==" << min('a','z') << endl;
cout << "min(3.14,2.72)==" << min(3.14,2.72) << endl;
cout << "min(\"123\",\"abc\")==" << min("123","abc",StrComp) << endl;
return 0;
}
#include <iostream> // std::cout
#include <algorithm> // std::min_element, std::max_element
bool myfn(int i, int j) { return i<j; }
struct myclass {
bool operator() (int i,int j) { return i<j; }
} myobj;
int main () {
int myints[] = {3,7,2,5,6,4,9};
// using default comparison:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7) << '\n';
// using function myfn as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myfn) << '\n';
// using object myobj as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myobj) << '\n';
return 0;
}
3. 練習(xí)
- 使用最大最小函數(shù)實(shí)現(xiàn)選擇排序敛滋。
template< class ForwardIt >
void selection( ForwardIt first, ForwardIt last);
template< class ForwardIt, class Compare >
void selection( ForwardIt first, ForwardIt last, Compare comp);