min/max函数既可以针对基本类型,也可以针对自定义类型。下面分这两种情况讲解一下:
一、基本类型
1、范围:即int / double / float / char / string / char * (字符串)
2、用法示例:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
int c = min(a,b);
}
二、自定义类型
(1)自定义类型需要先重载关系运算符
(2)示例:实现学生结构体的比较
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
struct Student{
public:
int numberID;
char name[20];
int score;
Student(){}
Student(int id_, char *name_, int score_){
numberID = id_;
strcpy(name, name_);
score = score_;
}
void in()
{
scanf("%d %s %d", &numberID, name, &score);
}
void out()
{
printf("%d %s %d\n", numberID, name, score);
}
};
bool min_cmp(Student S1, Student S2)
{
if(S1.score < S2.score) return true;
else if(S1.score > S2.score) return false;
else if(S1.score = S2.score)
{
if(S1.numberID < S2.numberID) return true;
else return false;
}
}
int main(int argc, const char * argv[])
{
Student s1,s2;
s1.in();
s2.in();
Student s3 = min(s1,s2,min_cmp);
s3.out();
return 0;
}
sort函数也是 Algorithm 中的常用函数, 默认为从小到大排序,第三个位置传参数改变排序方式。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
struct Student{
int numberID;
char name[20];
int score;
Student(){}
Student(int id_, char *name_, int score_){
numberID = id_;
strcpy(name, name_);
score = score_;
}
void in()
{
scanf("%d %s %d", &numberID, name, &score);
}
void out()
{
printf("%d %s %d\n", numberID, name, score);
}
bool operator < (const Student &S)const
{
if(this->score > S.score) return true;
else if(this->score < S.score) return false;
else if(this->score == S.score)
{
if(this->numberID < S.numberID) return true;
else return false;
}
}
};
bool max_cmp(Student S1, Student S2)
{
if(S1<S2) return true;
else return false;
}
int main(int argc, const char * argv[])
{
int n;
cin >> n;
Student stu[n];
for(int i=0;i<n;i++)
{
stu[i].in();
}
sort(stu,stu+n,max_cmp);
for(int i=0;i<n;i++)
{
stu[i].out();
}
return 0;
}