max()、min()、swap()简单介绍

来源:互联网 发布:pcb设计软件 编辑:程序博客网 时间:2024/06/05 09:58

这3个函数是<algorithm>算法程序库中的辅助函数,使用时需包含algorithm头文件。以下是max和min的源代码:


以上是max和min的简单形式,两个函数还存在另一个版本,具体源代码如下:


以下为第二种版本的max和min函数的验证试验,注意默认情况下max和min都会返回第二个元素b,所以在写comp比较函数时,注意当条件为真时返回第二个元素。

#include <iostream>#include <algorithm>using namespace std;struct test{int a;double b;};bool comp(test m,test n){if(m.a<n.a)return true;if(m.a>n.a)return false;}int main(){test smp1={2,8.45652};test smp2={4,1.23454};cout<<"smp1: "<<smp1.a<<" "<<smp1.b<<endl;cout<<"smp2: "<<smp2.a<<" "<<smp2.b<<endl;test smp3=max(smp1,smp2,comp);cout<<"smp3: "<<smp3.a<<" "<<smp3.b<<endl;return 0;}
swap函数源代码如下所示:

该函数使用较简单,不再介绍。

1 0
原创粉丝点击