STL

STL常见函数         讲课主播:刘孟良

1、swap 交换函数很常见不用多说

2、sort 快速排序  sort(a,a+n,cmp)

3、reverse    反转函数 reverse(a,a+n)

4、min max  通俗点选小选大,很常见

5、gcd 辗转相除求最大公约数 gcd(a,b)

int gcd(int x,int y)

{

if(y==0)

  return x;

else

  return gcd(y,x%y);

//return y==0?x:gcd(y,x%y);

}

6、Lower_bound&&Upper_bound

在有序数组中,从初到末二分查找,找一个比num大或相等&&大的数;

在从大到小的排序数组中,重载lower_bound()和upper_bound()lower_bound( begin,end,num,greater<type>() ):在从初到末

二分查找,找一个比num小或相等&&小的数。

#include<iostream>
#include<algorithm>
using namespace std;
int cmp(int x,int y)
{
return x>y;
}

int main()
{
int a[6]={1,5,3,1001,9543,47};
sort(a,a+6);
for(int i=0;i<=5;i++)
cout<<a[i]<<" ";
cout<<endl;
cout<<lower_bound(a,a+6,5)-a<<endl;   //注意-a
cout<<upper_bound(a,a+6,5)-a<<endl;
cout<<lower_bound(a,a+6,5)<<endl;
cout<<upper_bound(a,a+6,5)<<endl;
cout<<endl;
sort(a,a+6,cmp);
for(int i=0;i<=5;i++)
cout<<a[i]<<" ";
return 0;
}

7、Next_permutation

按字典序全排列

next_permutation提供升序、prev_permutation提供降序。

do
{
for(int i=1;i<=n;i++)
cout<<a[i]<<" ";
cout<<endl;
}while(next_permutation(a+1,a+n));

8、unique

去重 

int main()
{
cin>>n;
for(int i=0;i<=n-1;i++)
cin>>a[i];//以1 1 2 3 3 3 4 5 5 5为例。
sort(a,a+n);//unique(a, a+n)只能把相邻的数字中的多余部分放到数组后,并不是真正的删除。且只能处理相邻元素,所以使用时应先排序
int ans=unique(a,a+n)-a;
/*for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1);
int ans=unique(a+1,a+n+1)-a;*/
cout<<ans<<endl;
//第一次出现的是5,第二次是6
// 返回值是一个迭代器(迭代通俗点说 叫 一个个数过去,
//实现这样一个个数过去功能的东西,叫迭代器。),它指向的是去重后容器中
//不重复序列的最后一个元素的下一个元素的下标。
return 0;
}

 

posted @ 2020-02-27 20:40  赵学霖  阅读(98)  评论(0编辑  收藏  举报