文章目录
max()、min()和abs()
max(x,y)、min(x,y)分别访问x和y的最大值和最小值,且参数必须是两个。如果想返回三个数x、y、z的最大值,可以使用max(x,max(y,z))的写法.
abs(x)返回x的绝对值。
注意:x必须是整数,浮点型的绝对值用math从文件下的fabs
swap()
交换x和y的值
reverse()
reverse(it,it2)可以将数组指针在[it,it2)之间的元素或容器的迭代器在[it,it2)范围内的元素进行反转
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100]={1,2,3,4,5,6,7,8};
int main(){
reverse(a+2,a+7);
for(int i=0;i<8;i++)
cout<<a[i]<<" ";
}
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> vi;
int main(){
for(int i=1;i<=5;i++){
vi.push_back(i);
}
reverse(vi.begin()+2,vi.end());
for(int i=0;i<5;i++)
cout<<vi[i]<<" ";
}
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
string s="abcdef";
int main(){
reverse(s.begin()+2,s.begin()+5);
cout<<s<<endl;
}
next_permutation()
给出一个序列在全排列中的下一个序列
#include<cstdio>
#include<iostream>
#include<algorithm>
int a[10]={1,2,3};
using namespace std;
string s="abcdef";
int main(){
do{
printf("%d %d %d\n",a[0],a[1],a[2]);
}while(next_permutation(a,a+3));
}
fill()
fill()可以把数组或容器中的某一区间赋为某一相同的值。与memset不同,这里是数组类型对应范围中的任意值
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
char a[10];
int main(){
fill(a,a+5,'b');
cout<<a[2]<<endl;
}
sort()
用来排序的函数,根据具体情况使用不同的排序方法,效率较高
sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填))
不写比较函数,默认递增排序
基本数据类型数组的排序
bool cmp(int a,int b)
{
return a>b;//从大到小
}
结构体数组的排序
struct node{
int x,y;
};
bool cmp(const node&a,const node&b)
{
if(a.x!=b.x)
return a.x>b.x;//x为一级排序
else return a.y<b.y;//y为二级排序
}
容器的排序
在STL中,只有vector、string、deque是可以使用sort的。
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
string a[5]={"aaa","bbb","ccc"};
int main(){
sort(a,a+3,greater<string>());
for(int i=0;i<3;i++)
cout<<a[i]<<endl;
}
lower_bound()和upper_bound()
需要在一个有序数组或者容器中
lower_bound(first,last,val)用来寻找数组或者容器的[first,last)范围内第一个值大于等于val的位置,如果是数组,那返回该位置的指针;如果是容器,返回该位置的迭代器。
upper_bound(first,last,val)用来寻找在数组或者容器中的[first,last)范围内第一个值大于val的元素的位置。
若不用临时指针,想要直接查元素的下标,直接令返回值减去数组首地址即可
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
string a[10]={"aaac","aaab","bbbc"};
int main(){
printf("%d\n",lower_bound(a,a+3,"bbbc")-a);
}
max_element()、min_element
返回数组中最大位置的指针,减去首地址即所要找的元素的位置
如果有多个,找第一个
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int a[10]={5,4,6,7,8,3,2,6};
int main(){
printf("%d\n",*max_element(a,a+7));
printf("%d\n",min_element(a,a+7)-a);
}