頭文件
#include<algorithm>
用法:
1. max
2. min
3. abs(只能取整型的絕對值)
4. sort排序,復雜度:n*log(n)
1. 首先是升序排序
sort(a,a+n);//對a到a+n-1這n個元素進行默認的升序排序
2. 然后是定義一個比較函數實現降序排序
- 對數組
bool cmp1(int a,int b)
{
return a>b;//降序排列
//return a<b;//升序
}
sort(a,a+n,cmp1);
- 對結構體struct
第一種:定義比較函數
struct person{
int id;
char name[10];
};
person man[10];
bool cmp(person a,person b)
{
return a.id>b.id;//降序
//return a.id<b.id;//升序
}
sort(man,man+10,cmp);
第二種:重載運算符
struct person{
int id;
char name[10];
bool operator<(const person& s)
{
return id>s.id;//降序
//return id<s.id;//升序}
};
person man[10];
sort(man,man+10);
5. swap交換兩個數的值
6. reverse翻轉數組的值
reverse(a,a+10);
7. find 查找一個數的地址
int *p=find(a,a+10,2);//找到了p就是2的地址,沒找到p就是數組結尾
8. 填充函數:fill() 在區間內填充某一個值。
fill(a,a+10,2)//對a到a+n-1這n個元素賦值2
9. count 查找出現的次數
int p=count(a, a+10, 2);
10. 求最大公因數:__gcd()
int p= __gcd(a,b);
11. 求交集、並集、差集:set_intersection()、set_union()、set_difference()
12. 全排列:next_permutation()
int a[3] = {1,2,3};
do{
cout<<a[0]<<a[1]<<a[2]<<endl;
}while(next_permutation(a,a+3)); //輸出1、2、3的全排列