1. 简介
函数 |
作用 |
文档 |
max(a,b) |
返回两个元素中较大一个。 |
max() |
max(a,b,cmp) |
使用自定义比较操作cmp ,返回两个元素中较大一个。 |
max() |
max_element(beg,end) |
返回一个ForwardIterator ,指出[beg ,end )中最大的元素。 |
max_element() |
max_element(beg,end,cmp) |
使用自定义比较操作cmp ,返回一个ForwardIterator ,指出[beg ,end )中最大的元素。 |
max_element() |
min(a,b) |
返回两个元素中较小一个。 |
min() |
min(a,b,cmp) |
使用自定义比较操作cmp ,返回两个元素中较小一个。 |
min() |
min_element(beg,end) |
返回一个ForwardIterator ,指出[beg ,end )中最小的元素。 |
min_element() |
min_element(beg,end,cmp) |
使用自定义比较操作cmp ,返回一个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. 练习
- 使用最大最小函数实现选择排序。
template< class ForwardIt >
void selection( ForwardIt first, ForwardIt last);
template< class ForwardIt, class Compare >
void selection( ForwardIt first, ForwardIt last, Compare comp);