algorithm头文件下一些常用的函数(1)
1.max()和min()
这两个函数的参数必须是两个,分别返回这两个参数中的最大和最小值。
如果想要返回三个数的最大值,可以使用max(x,max(y,z))的写法,最小值同理。
2.abs()
abs(x)返回x的绝对值,但是x必须是整数,如果x是浮点数,应使用math头文件中的fabs()函数。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int x=-4;
cout<<abs(x);
}
输出结果:4
3.swap()
swap(x,y)可以用来交换x与y的值。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int x=1,y=2;
swap(x,y);
cout<<x<<" "<<y;
}
输出结果:2 1
4.reverse()
reverse(a,b)可以将[a,b)之间的元素或容器的迭代器在[a,b)之间进行反转。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[5]= {1,2,3,4,5};
reverse(a+1,a+3);
for(int i=0; i<5; i++)
cout<<a[i];
}
输出结果:13245
5.next_permutation()
next_permutation()可以给出一个序列在全排列中的下一个序列,在到达最后一个全排列时会返回false。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[3]= {1,2,3};
do
{
cout<<a[0]<<a[1]<<a[2]<<" ";
}
while(next_permutation(a,a+3)!=false);
}
输出结果:123 132 213 231 312 321
6.fill()
fill()可以将数组或容器的一段区间赋为相同的一个值。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[5]= {1,2,3,4,5};
fill(a,a+4,666);
for(int i=0; i<5; i++)
cout<<a[i]<<" ";
}
输出结果:666 666 666 666 5
7.sort()
sort()可以用来排序,有三个参数,分别是首元素地址,尾元素地址的下一个地址,比较函数。其中,前两个参数是必须填写的,而比较函数控制sort()排序的升降,不是必要填写,不填写时默认为升序。
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string a="baced";
string::iterator it=a.begin();
sort(it,it+3);
cout<<a;
}
输出结果:abced
如果使用比较函数
降序:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
p(int a,int b)
{
return a>b;
}
int main()
{
string a="baced";
string::iterator it=a.begin();
sort(it,it+3,p);
cout<<a;
}
输出结果:cbaed
升序:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
p(int a,int b)
{
return a<b;
}
int main()
{
string a="baced";
string::iterator it=a.begin();
sort(it,it+3,p);
cout<<a;
}
输出结果:abced
比较函数
p(int a,int b)
{
return a<b;
}
通过改变大于号小于号改变sort()的升降序。