当前位置 博文首页 > pzjdsg666的博客:C++:algorithm常用函数
C++网址:www.clpusplus.com
algorithm是C++一个常用的头文件,译为“算法”,其中有几个常用库函数。
#include<algorithm>
#include<iostream>
using namespace std;
int main(){
return 0;
}
sort一般用于结构体数组排序
default (1)
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
例:
#include<algorithm>
#include<iostream>
using namespace std;
int a[15],n;
bool cmp(int a,int b){
return a>b;
}
int main(){
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n,cmp);//cmp:排序顺序,不写则默认升序
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
5
1 2 3 4 5
5 4 3 2 1
max/min是求最大值/最小值的函数
格式:
max:
default (1)
template <class T> const T& max (const T& a, const T& b);
custom (2)
template <class T, class Compare>
const T& max (const T& a, const T& b, Compare comp);
min:
default (1)
template <class T> const T& min (const T& a, const T& b);
custom (2)
template <class T, class Compare>
const T& min (const T& a, const T& b, Compare comp);
#include<algorithm>
#include<iostream>
using namespace std;
int a,b;
int main(){
cin>>a>>b;
cout<<max(a,b)<<endl;//最大值
cout<<min(a,b);//最小值
return 0;
}
1 7
7
1
#include<algorithm>
#include<iostream>
using namespace std;
int a,b;
int main(){
cin>>a>>b;
cout<<max(max(a,b),c)<<endl;//最大值
cout<<min(min(a,b),c);//最小值
return 0;
}
1 2 3
3
1